Optimize Spring Boot test suite performance through context caching.
Spring's TestContext Framework caches application contexts based on their configuration "key". Tests with identical configurations reuse the same context.
- @ContextConfiguration
- @TestPropertySource
- @ActiveProfiles
- @WebAppConfiguration
- @MockitoBean definitions
- @TestConfiguration imports
@WebMvcTest(OrderController.class)
class OrderControllerTest1 {
@MockitoBean private OrderService orderService;
}
@WebMvcTest(OrderController.class)
class OrderControllerTest2 {
@MockitoBean private OrderService orderService;
}
// Same context reused@WebMvcTest(OrderController.class)
@ActiveProfiles("test")
class OrderControllerTest1 { }
@WebMvcTest(OrderController.class)
@ActiveProfiles("integration")
class OrderControllerTest2 { }
// Different contexts loadedmanagement:
endpoints:
web:
exposure:
include: metricsAccess: GET /actuator/metrics/spring.test.context.cache
logging.level.org.springframework.test.context.cache=DEBUG tests/
unit/ # No context
web/ # @WebMvcTest
repository/ # @DataJpaTest
integration/ # @SpringBootTest
Bad (multiple contexts):
@TestPropertySource(properties = "app.feature-x=true")
class FeatureXTest { }
@TestPropertySource(properties = "app.feature-y=true")
class FeatureYTest { }Better (grouped):
@TestPropertySource(properties = {"app.feature-x=true", "app.feature-y=true"})
class FeaturesTest { }Only when context state truly changes:
@Test
@DirtiesContext // Forces context rebuild after test
void testThatModifiesBeanDefinitions() { }- Group by configuration - Keep tests with same config together
- Limit property variations - Use profiles over individual properties
- Avoid @DirtiesContext - Prefer test data cleanup
- Use narrow slices - @WebMvcTest vs @SpringBootTest
- Monitor cache hits - Enable debug logging occasionally