在Spring项目中,对于controller、service、dao各层都需要建立单元测试项。对应不同的分层,我们可以使用junit和mock不同的方式。然而有些情况会需要启动spring容器来测试业务逻辑在容器内能否正常运行,针对此情况可参考如下单元测试方式。
SpringBoot增加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test<artifactId>
<scope>test</scope>
</dependency>
建立测试基类
- 新建JUnitBaseTest.java
package com.lucas.device;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.util.StopWatch;
import lombok.extern.slf4j.Slf4j;
/**
* <Description> <br>
*
* @author xubin<br>
* @version 1.0<br>
* @taskId <br>
* @CreateDate 2018年9月27日 <br>
*/
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class JUnitBaseTest {
/**
* sw 计时器<br>
*/
public static StopWatch sw = null;
/**
* Description: <br>
*
* @author xubin<br>
* @taskId <br>