Use one spring boot context through all SpringBootTests

此生再无相见时 提交于 2019-12-03 16:28:02
Andres Cespedes Morales

Ruslan, so your question is on how to reuse the Spring Boot Context for a JUnit Suite, right?

Then, it's almost out-of-the-box provided, you just need to annotate each unit test with the @SpringBootTest annotation.

Also make sure that your main @SpringBootApplication class is loading all the necessary @Configuration classes, this process will be automatically done if the @SpringBootApplication is on the root package above all configuration class and with the inherited @ComponentScan will load up all of them.

From the Spring Boot Testing documentation:

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

From the Spring Testing documentation:

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

Check this urls:

Main Takeaways:

  • Annotate each unit test with @SpringBootTest

  • Load all beans and necessary configuration classes in your main @SpringBootApplication class

  • IMPORTANT: Run a JUnit Suite, not a single JUnit test. Execute all tests as a group within your IDE.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!