在所有 SpringBootTest 中使用一个 Spring Boot 上下文

2024-04-28

我希望能够通过使用 junit 进行测试的不同类来缓存应用程序上下文。

测试类是这样声明的:

@SpringBootTest
@RunWith(SpringRunner.class)
public class SomeIntegrationTest {
}

我看到这个问题跨 junit 测试类重用 spring 应用程序上下文 https://stackoverflow.com/questions/8501975/reuse-spring-application-context-across-junit-test-classes但在这种情况下,我不使用任何 xml,并且我想完全启动上下文,而不仅仅是其中的几个 bean,所以@SpringBootTest比更适合@ContextConfiguration,如果我做对了。


Ruslan,所以您的问题是如何为 JUnit Suite 重用 Spring Boot 上下文,对吗?

然后,它几乎是开箱即用的,您只需使用以下注释来注释每个单元测试@SpringBootTest注解。

还要确保您的主要@SpringBootApplication类正在加载所有必需的@Configuration类,这个过程将自动完成,如果@SpringBootApplication位于所有配置类之上的根包上,并且具有继承的@ComponentScan将加载所有这些。

来自 Spring Boot 测试文档:

Spring Boot 提供了@SpringBootTest注释可以用作标准 spring-test 的替代@ContextConfiguration当您需要 Spring Boot 功能时。该注释的工作原理是通过 SpringApplication 创建测试中使用的 ApplicationContext。 Spring TestContext 框架将应用程序上下文存储在静态缓存中。这意味着上下文实际上存储在静态变量中。换句话说,如果测试在单独的进程中执行,则每次测试执行之间的静态缓存将被清除,这将有效地禁用缓存机制。 为了从缓存机制中受益,所有测试必须在同一进程或测试套件中运行。这可以通过在 IDE 中作为一个组执行所有测试来实现

来自 Spring 测试文档:

默认情况下,一旦加载,配置的 ApplicationContext 将在每个测试中重复使用。因此,每个测试套件仅产生一次设置成本,并且后续测试执行速度要快得多。在这种情况下,术语“测试套件”意味着所有测试都在同一个 JVM 中运行

检查这个网址:

  • http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testcontext-ctx-management-caching http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testcontext-ctx-management-caching
  • http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testing-ctx-management http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testing-ctx-management

主要要点:

  • 对每个单元测试进行注释@SpringBootTest

  • 在 main 中加载所有 bean 和必要的配置类@SpringBootApplication class

  • 重要提示:运行 JUnit Suite,而不是单个 JUnit 测试。在 IDE 中作为一个组执行所有测试。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在所有 SpringBootTest 中使用一个 Spring Boot 上下文 的相关文章

随机推荐