Spring Boot测试类能否重用应用程序上下文以加快测试运行速度?

vic*_*ass 13 java spring dependency-injection spring-test spring-boot

@ContextConfigurationlocation属性对Spring Boot集成测试没有意义.有没有其他方法可以在多个使用注释的测试类中重用应用程序上下文@SpringBootTest

Bra*_*ram 15

如果您从 Google 登陆此处并遇到启动多个应用程序上下文的问题,还请注意以下几点:

确保多次使用 @SpringBootTests 时使用相同的属性。例如,如果您有一个简单使用的测试@SpringBootTest,而另一个使用的测试,@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)每个测试都会启动自己的上下文!

最简单的方法是BaseIntegrationTest在每个集成测试中扩展一个类,并将@SpringBootTest注释放在该基类上,例如:

package com.example.demo;

import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public abstract class BaseIntegrationTest{
}
Run Code Online (Sandbox Code Playgroud)


lub*_*nac 11

是.实际上它是默认行为.链接指向Spring Framework文档,Spring Boot使用它.

顺便说一句,默认情况下也会重复使用上下文@ContextConfiguration.

  • 也许将 vicusbass 指向文档是个好主意?https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications (3认同)

Ros*_*tha 8

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
Run Code Online (Sandbox Code Playgroud)

上面的注释表示完整的上下文已加载,并且在测试中使用相同的上下文。这意味着它只加载一次。

Spring Boot 提供了 @SpringBootTest 注解,当您需要 Spring Boot 功能时,可以将其用作标准 spring-test @ContextConfiguration 注解的替代方案。该注释的工作原理是通过 SpringApplication 创建测试中使用的 ApplicationContext

  • 这就是我的测试的配置方式。但是,我有“@DirtiesContext”注释,这就是为每个测试类重新启动所有内容的原因。`@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)` 我正在调查是否可以删除它,但到目前为止我发现表存在一些问题 (4认同)

rco*_*len 6

对于像我这样从 Google 登陆的人:

如果您有<reuseFork>false</reuseFork>Maven surefire 插件,那么您的上下文就不可能被重用,因为您正在为每个测试类有效地生成一个新的 JVM。

这在 Spring 文档中有详细记录:https : //docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#testcontext-ctx-management-caching