一,我们的结构如下
二,代码UnitTestApplication
package com.nl; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * spring-boot-starter-web * spring-boot-starter-test * 这两个包是必须的 */ @SpringBootApplication public class UnitTestApplication { public static void main(String[] args) { System.out.println("test"); SpringApplication.run(UnitTestApplication.class, args); } }
三,UnitTest
import com.nl.UnitTestApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * UnitTestApplication为当前模块启动,记住必须是启动,不然test会报异常 */ @RunWith(SpringRunner.class) @SpringBootTest(classes = UnitTestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class UnitTest { @Test public void SayTest() { System.out.println("Test"); } }
四,注意点
1》必须要引入以下两个包
<!--单元测试必须引入这两个包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <!--单元测试必须引入这两个包-->
2》单元测试的启动项的配置必须是项目的启动类,本文是UnitTestApplication
源码git地址:https://gitee.com/mt_chen/nl-spring-boot.git