我希望能够通过使用 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
检查这个网址:
- > 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
要点:
用
@SpringBootTest
注释每个单元测试在您的主
@SpringBootApplication
类中加载所有 beans 和必要的配置类重要提示:运行 JUnit 套件,而不是单个 JUnit 测试。在您的 IDE 中作为一个组执行所有测试。