通过所有 SpringBootTests 使用一个 spring 引导上下文

Use one spring boot context through all SpringBootTests

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

测试 类 以这种方式声明:

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

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

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

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

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

来自 Spring 引导测试文档:

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

  • 注释每个单元测试
  • 加载所有 beans 和必要的配置 classes 在你的 main @SpringBootApplication class

  • 重要提示:运行 JUnit 套件,而不是单个 JUnit 测试。在 IDE.

  • 中作为一个组执行所有测试