前提:Spring环境已经搭建完毕
1.pom.xml文件下添加juint的依赖
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope></dependency>
注意:版本4.0以上,否则无法使用注解机制
2.pom.xml文件下添加spring-test的依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.5.RELEASE</version></dependency>
切记:把<scope></scope>标签去掉 否则无法使用 @ContextConfiguration
3.在Resources文件夹下新建test文件用于存放所有单元测试类,并Mark as test Sources,否则你将遇到一系列令你头疼或蛋疼的问题,比如Cannot resolve symbol @Runwith(),找不到junit相关的包等等.
4.创建BaseTest类,该类是所有单元测试的基础类,并实现@After 和@Before 下的两个方法,用于统计你要测试的方法执行了多长时间,以此判断你的代码的性能。
import org.junit.After;import org.junit.Before;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/** * Author: aAron * Date: 2018/4/7 13:24 * Description: Spring单元测试类的基础类 */
@RunWith(SpringJUnit4ClassRunner.class)//使用Springjuint4的Runner @ContextConfiguration(locations = {"classpath:applicationContext.xml"})//指定Spring的配置文件,这样便可以从IOC容器中取出你要使用的对象public class BaseTest { private long beforeTime; private long afterTime; @Before public void before(){ beforeTime=System.currentTimeMillis(); } @After public void after(){ afterTime=System.currentTimeMillis(); System.out.println("该方法共执行了:"+(afterTime-beforeTime)+" 毫秒"); }}
5.创建你的测试方法并继承与BaseTest。
import com.tpk.curd.bean.Department; import com.tpk.curd.dao.DepartmentMapper; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Author: aAron * Date: 2018/4/7 13:37 * Description: 测试EmployeeMapperx\相关接口 */ public class TestEmployeeMapper extends BaseTest { @Autowired private DepartmentMapper departmentMapper; @Test public void insertTest(){ Department department=new Department(); department.setDepName("研发部"); departmentMapper.insert(department); } }
6.完美。