Spring+junit4 实现注解测试原理解析。

来源:互联网 发布:mac和手机 日历同步 编辑:程序博客网 时间:2024/06/05 22:59
背景:
  我们在使用Spring集成的项目进行开发的时候,需要在不依赖web容器启动的时候去进行单元测试,而Spring为我们提供了相应单元测试框架,在spring 的org.springframework.test.context包内,我们只要在单元测试中引入相应的注解,就可以轻松的实现单元测试。其实好的单元测试可以大大提高我们的生产力,加快我们的开发速度。
      junit单元测试优势:1、不用在每个类里面都写main方法,然后去测试。
     2、可以得到每个方法执行所消耗的 时间,不用自己计算。
     junit单元测试环境搭建:
spring集成Junit4需要两个jar包:junit-4.10.jar和spring-test-4.2.0.RELEASE.jar。
  使用方法
  下图是我自己写的一个测试类的方法。
  使用很简单
   1)加入Junit4的注解 @RunWith,在这里可以指定Spring的的运行器来集成。
 2)加入@ContextConfiguration注解,指定要加载的配置文件的位置。
   实例:
package com.mqAction;import java.util.Date;import java.util.List;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.common.common.entity.SmsRecord;import com.common.common.service.ISmsRecordService;@RunWith(SpringJUnit4ClassRunner.class)  //使用junit4进行测试  @ContextConfiguration(locations={"classpath*:spring-mybatis.xml"})   public class FilterMain {@Autowiredprivate ISmsRecordService smsRecordService;//判断数据插入是否成功,并且返回插入主键编号@Testpublic void test(){SmsRecord smsRecord =new SmsRecord();smsRecord.setAppType("wlsq");smsRecord.setCreateTime(new Date());smsRecord.setEntranceType(1);smsRecord.setIdentification(0);smsRecord.setJim("6e0fc0fddd294862a51764bf67a151ee");smsRecord.setMessageId("ox11102202");smsRecord.setPushType("wlsq");smsRecord.setTelephone("13265740591");int id = smsRecordService.insert(smsRecord);System.out.println("返回主键Id:"+smsRecord.getId());}//数据查询(通过)@Testpublic void test1(){SmsRecord smsRecord =new SmsRecord();smsRecord.setId(231);List<SmsRecord> list= smsRecordService.selectByObject(smsRecord);System.out.println("返回主键Id:"+list.get(0).getMessageId());}//数据更改操作@Testpublic void test2(){SmsRecord smsRecord =new SmsRecord();smsRecord.setId(237);smsRecord.setIdentification(1);smsRecord.setUpTime(new Date());int result = smsRecordService.updateByPrimaryKeySelective(smsRecord);System.out.println("更新数据数量:"+result);}}



0 0