bit*_*xyz 6 spring-boot spring-boot-test
我正在开发一个 Spring Boot 应用程序并编写一些 junit 测试。
但是我发现当我运行任何测试时,tomcat也会启动,这使得这些测试非常慢并且浪费了很多时间。
当我开发SpringMvc应用程序时,junit测试可以在不启动tomcat的情况下运行,它节省了很多时间。
所以,我想问一下是否可以在不启动tomcat的情况下运行springboot测试?
默认情况下,使用 @SpringBootTest 运行测试不会启动嵌入式服务器。默认情况下,它运行在MOCK环境中。
默认情况下,@SpringBootTest不会启动服务器。您可以使用 @SpringBootTest 的 webEnvironment 属性来进一步优化测试的运行方式:
MOCK(默认):加载 Web ApplicationContext 并提供模拟 Web 环境。使用此注释时,不会启动嵌入式服务器。如果您的类路径上没有可用的 Web 环境,则此模式会透明地回退到创建常规的非 Web ApplicationContext。它可以与 @AutoConfigureMockMvc 或 @AutoConfigureWebTestClient 结合使用,对 Web 应用程序进行基于模拟的测试。
我想你想要实现的目标可以通过切片测试概念来实现。一般来说,当你执行单元测试时,你不需要一个成熟的模拟环境或带有嵌入式服务器的环境,并且所有配置的bean都在spring容器中。
例如,您必须对控制器进行单元测试,然后您有@WebMvcTest注释,该注释将仅配置与 Web 相关的 bean 并忽略其余的 bean。
要测试 Spring MVC 控制器是否按预期工作,请使用 @WebMvcTest 注释。@WebMvcTest 自动配置 Spring MVC 基础结构,并将扫描的 bean 限制为 @Controller、@ControllerAdvice、@JsonComponent、Converter、GenericConverter、Filter、WebMvcConfigurer 和 HandlerMethodArgumentResolver。使用此注释时,不会扫描常规 @Component bean。
同样,对于数据库层,还有@DataJpaTest
长话短说:当您打算使用 Spring 框架进行单元测试时,大多数情况下您应该使用切片测试。
DEB*_*NDA -2
如果您放置以下注释,这将启动嵌入式容器......
@RunWith(SpringRunner.class)
@SpringBootTest
Run Code Online (Sandbox Code Playgroud)
因为,如果您看到该类SpringBootTestContextBootstrapper.class,则它已被调用@BootstrapWith(SpringBootTestContextBootstrapper.class)当我们指定时 调用的容器@SpringBootTest
您可以删除它们并执行以下操作:
import org.junit.Test;
public class HellotomApplicationTests {
@Test
public void contextLoads() {
}
}
Run Code Online (Sandbox Code Playgroud)
R-Click 和 RunAs Junit
| 归档时间: |
|
| 查看次数: |
7899 次 |
| 最近记录: |