一、环境
在SpringBoot环境中添加单元测试maven依赖,依赖如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
二、关键注解介绍
@RunWith(SpringJUnit4ClassRunner.class),这是JUnit的注解,通过这个注解让SpringJUnit4ClassRunner这个类提供Spring测试上下文。
@SpringApplicationConfiguration(classes = 启动类.class),这是Spring Boot注解,为了进行集成测试,需要通过这个注解加载和配置Spring应用上下文。这是一个元注解(meta-annoation),它包含了@ContextConfiguration( loader = SpringApplicationContextLoader.class)这个注解,测试框架通过这个注解使用Spring Boot框架的SpringApplicationContextLoader加载器创建应用上下文。
@WebAppConfiguration 表明是WEB应用环境,不能和@WebIntegrationTest一起使用
@WebIntegrationTest(“server.port:0”),这个注解表示当前的测试是集成测试(integration test),因此需要初始化完整的上下文并启动应用程序。这个注解一般和@SpringApplicationConfiguration一起出现。server.port:0指的是让Spring Boot在随机端口上启动Tomcat服务,随后在测试中程序通过@Value(“${local.server.port}”)获得这个端口号,并赋值给port变量。当在Jenkins或其他持续集成服务器上运行测试程序时,这种随机获取端口的能力可以提供测试程序的并行性。
@SpringBootTest(classes = AppApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK) 指定启动类,web环境
WebEnvironment.MOCK—提供一个Mock的Servlet环境,内置的Servlet容器并没有真实的启动,主要搭配使用@AutoConfigureMockMvc
WebEnvironment.RANDOM_PORT — 提供一个真实的Servlet环境,也就是说会启动内置容器,然后使用的是随机端口
WebEnvironment.DEFINED_PORT — 这个配置也是提供一个真实的Servlet环境,使用的默认的端口,如果没有配置就是8080
WebEnvironment.NONE — 这是个神奇的配置,跟Mock一样也不提供真实的Servlet环境。
推荐使用方式:
在SpringBOOT项目创建的时候,会自动在测试启动类上标有以下注解