@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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容