IDEA Spring环境下的单元测试

本文介绍如何在Spring环境中进行单元测试,包括配置JUnit和Spring Test依赖、设置测试资源目录、创建基础测试类及具体测试方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前提: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.完美。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值