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.

k13i
  • 4,011
  • 3
  • 35
  • 63

1 Answers1

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).

Leonard Brünings
  • 12,408
  • 1
  • 46
  • 66
  • 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 Apr 14 '19 at 09:39
  • k13i good that you found out the difference, could you please accept the answer. – Leonard Brünings Apr 14 '19 at 19:17
  • 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? – jaco0646 Apr 19 '19 at 23:58
  • 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. – Leonard Brünings Apr 21 '19 at 12:36