@SpringBootTest
@SpringBootTest注解告诉SpringBoot去寻找一个主配置类(例如带有@SpringBootApplication的配置类),并使用它来启动Spring应用程序上下文。SpringBootTest加载完整的应用程序并注入所有可能的bean,因此速度会很慢。
在这种情况下,不需要创建 MockMvc bean,可以直接通过RestTemplate进行请求测试(或者使用TestRestTemplate)。
@WebMvcTest
@WebMvcTest注解主要用于controller层测试,只覆盖应用程序的controller层,HTTP请求和响应是Mock出来的,因此不会创建真正的连接。因此需要创建 MockMvc bean进行模拟接口调用。
如果Controller层对Service层中的其他bean有依赖关系,那么需要使用Mock提供所需的依赖项。
WebMvcTest要快得多,因为我们只加载了应用程序的一小部分。
Slice 注解
有时,我们仅希望测试应用程序的一个简单片段(Slice),而不是自动配置整个应用程序。Spring Boot 1.4引入了4个新的测试注释:
@WebMvcTest - for testing the controller layer@JsonTest - for testing the JSON marshalling and unmarshalling@DataJpaTest - for testing the repository layer@RestClientTests - for testing REST clients复制代码
使用场景
@WebMvcTest用于从服务器端对Controller层进行统一测试;如果需要从客户端与应用程序交互时,应该使用@SpringBootTest做集成测试。