@SpringBootTest注解进行单元测试

/ Java / 没有评论 / 1725浏览

@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: