Spring Test Framework provides context caching to improve test performance by reusing ApplicationContext instances across multiple test classes when they share the same configuration.
How Context Caching Works
Spring generates a cache key based on:
- Context Loader - The class responsible for loading the context
- Locations & Classes - Configuration files/classes specified in @ContextConfiguration
- Active Profiles - Profiles activated via @ActiveProfiles
- Property Sources - Test property sources from @TestPropertySource
- Context Initializers - Custom context initializers
- Context Customizers - Customizers from test slices like @WebMvcTest
🎯 Cache Hit
When a test class has the same exact configuration as a previous test, Spring reuses the existing ApplicationContext. This results in faster test execution.
🔄 Cache Miss
When a test class has a different configuration, Spring creates a new ApplicationContext. This takes more time but ensures test isolation.
Optimization Tips
- Group similar tests: Use the same @ContextConfiguration across related test classes
- Minimize @DirtiesContext: Avoid marking contexts as dirty unless absolutely necessary
- Use test slices: @WebMvcTest, @DataJpaTest create focused, cacheable contexts
- Consolidate profiles: Use consistent @ActiveProfiles across test classes
📚 Learn More
For detailed information about Spring Test context caching: