📚 开源资源分享——颜佐光的个人书架
✉️ 联系站长
书架 / Java / SpringBoot

@SpringBootTest注解进行单元测试

2020-11-06 16:57 · 约 1,004 字 · 浏览 2,429 次SpringBoot

@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

← 返回《Java》目录书架 →