ASP站长网在工作中,很多项目是基于ssm框架的web项目,在编写完代码需要进行测试。但是对象都交由Spring容器进行对象管理之后,测试变得复杂了。因为所有的Bean都需要在applicationContext.xml中加载好,之后再通过@Resource去取得。如果每次都要整个业务流做的差不多了再去测试,这样效率很低,很多同学可能是通过web端发请求进行触发测试。有时候,我们仅仅是需要测试我们dao层sql是否正确,但是确要重启服务器,在浏览器发送请求进行测试,或者写个定时器触发测试。这很费事费时。所以,我们想到Junit能否帮助我们测试。
 
1、使用maven,添加Junit依赖
 
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <!-- 表示开发的时候引入,发布的时候不会加载此包 -->
    <scope>test</scope>
</dependency>
 
2、使用Junit中的@RunWith注解(Junit测试框架以后好好研究一下)
 
 @Runwith:即测试运行器,放在测试类名之前,用来确定测试类怎么运行的,当不指定这个注解时,使用默认Runner来运行测试代码,即@RunWith(JUnit4.class)。
 
 @RunWith(SpringJUnit4ClassRunner.class)集成了Spring的一些功能。
 
package com.mdd.mt;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
import com.mdd.pip.crawler.QuanWanProxyIpCrawler;
import com.mdd.pip.pipeLine.DataPipeLine;
 
import us.codecraft.webmagic.Spider;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-mybatis.xml")
public class ServiceTest{
   
    @Autowired
    private QuanWanProxyIpCrawler quanWanProxyIpCrawler;
   
    @Autowired
    private DataPipeLine dataPipeLine;
   
    @Test
    public void testSaveProxyIpList(){
        Spider.create(quanWanProxyIpCrawler)
            .addPipeline(dataPipeLine)
            .addUrl("http://www.linuxidc.com/").thread(5).run();
    }
 
}

dawei

【声明】:九江站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。