gpt4 book ai didi

java - 通过所有 SpringBootTests 使用一个 spring boot 上下文

转载 作者:搜寻专家 更新时间:2023-11-01 02:37:13 24 4
gpt4 key购买 nike

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

测试类是这样声明的:

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

我看到了这个问题Reuse spring application context across junit test classes但在这种情况下,我不使用任何 xml,我想完全启动上下文,而不仅仅是其中的几个 beans,所以 @SpringBootTest@ContextConfiguration 更合适,如果我做对了。

最佳答案

Ruslan,所以你的问题是关于如何为 JUnit 套件重用 Spring Boot 上下文,对吗?

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

还要确保您的主要@SpringBootApplication 类正在加载所有必需的@Configuration 类,如果@SpringBootApplication 位于所有配置类之上的根包中,继承的 @ComponentScan 将加载所有配置类。

来自 Spring Boot 测试文档:

Spring Boot provides a @SpringBootTest annotation which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext used in your tests via SpringApplication. The Spring TestContext framework stores application contexts in a static cache. This means that the context is literally stored in a static variable. In other words, if tests execute in separate processes the static cache will be cleared between each test execution, and this will effectively disable the caching mechanism. To benefit from the caching mechanism, all tests must run within the same process or test suite. This can be achieved by executing all tests as a group within an IDE

来自 Spring 测试文档:

By default, once loaded, the configured ApplicationContext is reused for each test. Thus the setup cost is incurred only once per test suite, and subsequent test execution is much faster. In this context, the term test suite means all tests run in the same JVM

检查这个网址:

要点:

  • @SpringBootTest注释每个单元测试

  • 在您的主 @SpringBootApplication 类中加载所有 beans 和必要的配置类

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

关于java - 通过所有 SpringBootTests 使用一个 spring boot 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45591160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com