@SpringBootTest注解进行单元测试

概述

@SpringBootTest注解是SpringBoot Since:1.4.0 版本开始引入的一个用于测试的注解。基本用法如下:

添加的依赖

 
            org.springframework.boot
            spring-boot-starter-test
            test
        

需要测试的类


    @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

你可能感兴趣的:(@SpringBootTest注解进行单元测试)