【问题标题】:how to run springboot test without run tomcat?如何在不运行 tomcat 的情况下运行 spring boot 测试?
【发布时间】:2019-09-23 21:36:27
【问题描述】:

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

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

我在开发SpringMvc应用时,不启动tomcat也可以运行junit test,省了很多倍。

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

【问题讨论】:

  • 你能把你检测到tomcat启动的日志贴出来吗??
  • 你能提供给我们你的测试类的sn-ps吗?我的测试用 @RunWith(SpringRunner.class) 注释,并且运行 mvn test 时没有启动 tomcat

标签: spring-boot spring-boot-test


【解决方案1】:

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

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

MOCK(Default) : 加载一个 web ApplicationContext 并提供一个模拟 web 环境。使用此功能时不启动嵌入式服务器 注解。如果您的类路径上没有可用的 Web 环境, 这种模式透明地回退到创建一个常规的非网络 应用程序上下文。它可以与 @AutoConfigureMockMvc 或 @AutoConfigureWebTestClient 用于基于模拟 测试您的网络应用程序。

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

我猜你想要达到的目标可以通过切片测试的概念来实现。一般来说,当您执行单元测试时,您不需要一个成熟的模拟环境带有嵌入式服务器的环境,所有配置的bean都在spring容器中。

例如你必须对你的 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 框架进行单元测试时,切片测试是一种您应该在大多数情况下使用

【讨论】:

    【解决方案2】:

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

    @RunWith(SpringRunner.class)
    @SpringBootTest
    

    因为,如果你看到 SpringBootTestContextBootstrapper.class 类,这已经被调用了当我们指定 @SpringBootTest 时由 @BootstrapWith(SpringBootTestContextBootstrapper.class) 调用的容器

    您可以删除它们,并且可以执行以下操作:

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

    R-Click 和 RunAs Junit

    O/P

    【讨论】:

      猜你喜欢
      • 2019-03-17
      • 1970-01-01
      • 2017-07-06
      • 2011-06-13
      • 2022-10-01
      • 2023-04-04
      • 1970-01-01
      • 2023-03-18
      • 2021-11-15
      相关资源
      最近更新 更多