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;

@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.goubanjia.com/").thread(5).run();
    }

}

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

这里参考了

http://jackroomage.iteye.com/blog/1741767

Junit测试框架

https://my.oschina.net/pangyangyang/blog/146015

 

转载于:https://www.cnblogs.com/xwlhyy1072552712/p/6985919.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值