如何在不运行tomcat的情况下运行springboot测试?

时间:2019-05-06 09:06:31

标签: spring-boot spring-boot-test

我正在开发一个Spring Boot应用程序并编写一些junit测试。

但是我发现当我运行任何测试时,tomcat也会启动,这会使那些测试非常缓慢并且浪费很多时间。

当我开发SpringMvc应用程序时,无需启动tomcat就可以运行junit测试,这样可以节省很多时间。

那么,我还是想问问它是否在没有启动tomcat的情况下运行springboot测试?

2 个答案:

答案 0 :(得分:0)

默认情况下,使用@SpringBootTest运行测试不会启动嵌入式服务器。 默认情况下,它在MOCK环境中运行。

  

默认情况下,@ SpringBootTest不会启动服务器。您可以使用   @SpringBootTest的webEnvironment属性可进一步优化您的   测试运行:

     

MOCK(默认):加载Web ApplicationContext并提供模拟Web   环境。使用此功能时无法启动嵌入式服务器   注解。如果您的类路径中没有网络环境,   此模式透明地回退到创建常规非网络   ApplicationContext。可以结合使用   @AutoConfigureMockMvc或@AutoConfigureWebTestClient(基于模拟)   测试您的Web应用程序。

文档链接:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications

我想您想要实现的目标可以通过 Slice Test 概念来实现。通常,执行单元测试时,不需要在弹簧容器中具有所有已配置bean的成熟的模拟环境或带有嵌入式服务器的环境

例如您必须对 Controller 进行单元测试,然后具有 @WebMvcTest 批注,该批注将仅配置与Web相关的bean,而忽略其余的bean。

  

要测试Spring MVC控制器是否按预期工作,请使用   @WebMvcTest批注。 @WebMvcTest自动配置Spring MVC   基础架构并将扫描到的bean限制为@Controller,   @ ControllerAdvice,@ JsonComponent,转换器,GenericConverter,   筛选器,WebMvcConfigurer和HandlerMethodArgumentResolver。定期   使用此批注时,不会扫描@Component bean。

文档链接:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests

类似地,对于数据库层,有 @DataJpaTest

文档链接:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-jpa-test

长话短说:当您打算使用Spring框架进行单元测试时,切片测试是大多数情况下应使用的

答案 1 :(得分:-1)

如果要放置以下注释,这将启动嵌入式容器...

@RunWith(SpringRunner.class)
@SpringBootTest

因为,如果您看到SpringBootTestContextBootstrapper.class类,则该容器已被我们指定@BootstrapWith(SpringBootTestContextBootstrapper.class)的容器@SpringBootTest调用

您可以删除这些内容并执行以下操作:

import org.junit.Test;    
public class HellotomApplicationTests {    
    @Test
    public void contextLoads() {
    }

}

R-Click和RunAs Junit

O / P enter image description here

相关问题