1.准备工作:
Junit 4.7以上版本+ 项目中有spring-test jar包的引入(由于本人测试过程中,使用4.3版本时遇到版本问题,改用4.7以上版本解决问题。而找jar包竟然浪费了一点时间,果断保存 百度云 链接:https://pan.baidu.com/s/1WHaGqotGC29EP-et9KHI_g 密码:41y4 需要者自取)
2.jar包引入后
通常情况下我们在mapper配置文件及接口文件 和 service层写好 某个方法,然后进行单元测试
在测试类中这样写一段代码:
package com.huiyou.ljk.test;
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.huiyou.ljk.data2.entity.Customer;
import com.huiyou.ljk.data2.service.CustomerService;
/**
* @ClassName: JunitTest
* @Description: TODO(这里用一句话描述这个类的作用)
* @Author MrZ
* @Version 2018年6月15日
*
*/
@ContextConfiguration(locations= {"classpath:spring.xml"}) //主要代码 1.指向spring核心配置文件
@RunWith(SpringJUnit4ClassRunner.class) //主要代码2
public class JunitTest {
@Autowired
private CustomerService customerService;
@Test
public void getCustomer() {
try {
Customer customer = customerService.getCustomerById("1");
System.out.println(customer.getCcuscode());//此时应该输出数据库的结果: 1
} catch (Exception e) {
e.printStackTrace();
System.out.println("error");
}
}
}
红色标记我的测试类,蓝色是相关类的引入 ,Junit配合spring-test的单元测试。
主要代码在绿色部分locations指向你的spring核心配置文件。如果你的Junit包在4.7版本一下可能在敲完绿色的代码后就会有小红叉的出现,是因为低版本的junit缺少一个类,需要引入其他jar包,或直接使用4.7以上版本解决此问题。