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

背景:
  我们在使用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 {
    @Autowired
    private ISmsRecordService smsRecordService;

    //判断数据插入是否成功,并且返回插入主键编号
    @Test
    public 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());

    }
    //数据查询(通过)
    @Test
    public void test1(){
        SmsRecord smsRecord =new SmsRecord();
        smsRecord.setId(231);


        List<SmsRecord> list= smsRecordService.selectByObject(smsRecord);
        System.out.println("返回主键Id:"+list.get(0).getMessageId());

    }

    //数据更改操作
    @Test
    public 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);

    }








}



转自:http://blog.csdn.net/zhouzhiwengang/article/details/53068312

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值