Spring整合Junit测试框架

在工作中,很多项目是基于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;

}

再进行测试就很方便了,对于测试框架Junit还有很多功能,后续继续学习,补充。

猜你喜欢

转载自www.linuxidc.com/Linux/2018-09/153991.htm