Spring+junit4实现注解单元测试

以往在做单元测试时需要编码进行spring环境启动,这样比较繁琐,最近在了解到,可以用注解简单的实现单元测试,现在总结一下。

junit单元测试环境搭建:

spring集成junit4需要两个jar包:junit-4.10.jar和spring-test-4.2.0.RELEASE.jar

使用方法:

1)加入junit的注解@RunWith,在这里可以指定spring的运行器来集成。

2)加入@ContextConfiguration注解,指定要加载的配置文件位置。

接下来上示例:

package com.testAction;
 
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.tranceRecord;
import com.common.common.service.TranceRecordService;

@RunWith(SpringJUnit4ClassRunner.class)  //使用junit4进行测试  
@ContextConfiguration(locations={"classpath*:spring-mybatis.xml"})   
public class FilterMain {
	@Autowired
	private TranceRecordService tranceRecordService;	

	//判断数据插入是否成功,并且返回插入主键编号
	@Test
	public void test(){
		TranceRecord tranceRecord =new TranceRecord();
		tranceRecord.setAppType("wlsq");
		tranceRecord.setCreateTime(new Date());
		tranceRecord.setEntranceType(1);
		tranceRecord.setIdentification(0);
		tranceRecord.setScrect("6dsd3455f34890vf5464bm665262");
		tranceRecord.setMessageId("ox32125673");
		tranceRecord.setPushType("wxid");
		tranceRecord.setTelephone("13254340578");

		int id = tranceRecordService.insert(tranceRecord);
		System.out.println("返回主键Id:"+tranceRecord.getId());	
	}

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

		List list= tranceRecordService.selectByObject(tranceRecord);
		System.out.println("返回主键Id:"+list.get(0).getMessageId());
	}

	//数据更改操作
	@Test
	public void test2(){
		TranceRecord tranceRecord =new TranceRecord();
		tranceRecord.setId(237);
		tranceRecord.setIdentification(1);
		tranceRecord.setUpTime(new Date());

		int result = tranceRecordService.updateByPrimaryKeySelective(tranceRecord);
		System.out.println("更新数据数量:"+result);
	}
}

你可能感兴趣的:(工具)