@SpringBootTest注解进行单元测试
概述
@SpringBootTest注解是SpringBoot Since:1.4.0 版本开始引入的一个用于测试的注解。基本用法如下:
添加的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
需要测试的类
@GetMapping("/health")
public String health() {
return HttpStatus.OK.getReasonPhrase();
}
单元测试类
/**
* @Description TODO
* @Date 2019/5/5 11:37
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HealthControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void testHealth() throws Exception {
this.mvc.perform(MockMvcRequestBuilders.get("/health")).andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().string("OK"));
}
}
参考官网DOC:
- https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html
- 代码地址:https://github.com/shihongwei/okhttp-demo.git
本文由 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为: 2020/11/06 08:57