Can Spring Boot test classes reuse application context for faster test run?
Solution 1
Yes. Actually it is default behavior. The link point to Spring Framework docs, which is used by Spring Boot under the hood.
BTW, context is reused by default also when @ContextConfiguration
is used as well.
Solution 2
For those like me landing from Google:
If you have <reuseFork>false</reuseFork>
in your Maven surefire plugin, there is no chance your context can be reused, as you're effectively spawning a new JVM for each test class.
This is well documented in Spring Documentation: https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#testcontext-ctx-management-caching
Solution 3
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
The above annotation says the complete context is loaded and same is used across the tests. It means it's loaded once only.
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
Solution 4
If you land here from Google and have an issue with multiple application contexts being started, also take note of this:
Make sure that when you use @SpringBootTests multiple times that you use the same properties.
E.g. if you have one test using simply @SpringBootTest
and another one using @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
each will spin up its own context!
Easiest would be to have a BaseIntegrationTest
class which you extend in every integration test and put the @SpringBootTest
annotation on that base class, e.g.:
package com.example.demo;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public abstract class BaseIntegrationTest{
}
vicusbass
Updated on December 16, 2021Comments
-
vicusbass over 2 years
@ContextConfiguration
location attribute does not make sense for Spring Boot integration testing. Is there any other way for reusing application context across multiple test classes annotated with@SpringBootTest
?