0

I would like to reuse the same Spring context across several integration tests written in Spock framework. According to the documentation context caching is based on classes property of @ContextConfiguration annotation.

That's an example test:

@SpringBootTest
@ContextConfiguration(classes = Application.class)
class ExampleIntegrationTest extends Specification {

    def 'should reuse Spring context if already created'() {
        expect:
        1 == 1
    }
}

The second test also contains the same @ContextConfiguration annotation, i.e.

@ContextConfiguration(classes = Application.class)

but when I run all tests I can see in the console that Spring context is created per each test. I would like to cache it between different tests. Am I missing something? Basically, I would like to achieve the same thing as described here (stackoverflow question) but in Spock instead of JUnit.

1 Answer 1

2

Context Caching is done by the Spring Framework, it follows the rules described here, i.e., it builds a context cache key factoring in different factors. As long as all of them are the same, it reuses the same context.

  • locations (from @ContextConfiguration)
  • classes (from @ContextConfiguration)
  • contextInitializerClasses (from @ContextConfiguration)
  • contextCustomizers (from ContextCustomizerFactory)
  • contextLoader (from @ContextConfiguration)
  • parent (from @ContextHierarchy)
  • activeProfiles (from @ActiveProfiles)
  • propertySourceLocations (from @TestPropertySource)
  • propertySourceProperties (from @TestPropertySource)
  • resourceBasePath (from @WebAppConfiguration)

Spock supports @SpringBootTest or any of the other Spring Boot test annotations, such as @WebMvcTest, directly and you should not add an explicit @ContextConfiguration(classes = Application.class).

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your answer. Finally it turned out that tests were running with different profiles and that's why Spring did not reuse the context.
k13i good that you found out the difference, could you please accept the answer.
My tests are not sharing a context even though they share a common base class annotated with @SpringBootTest(webEnvironment = RANDOM_PORT, classes = [MyTestConfig, MyApp]). The annotations listed above are not used at all. How can I troubleshoot the context caching?
You can see what is going on, by setting the logger org.springframework.test.context.cache to DEBUG. If you are using @MockBean then this will also prevent reuse.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.