Application context caching reuses configured, running Spring test applications across compatible test classes. It reduces repeated startup work, which matters when application initialization consumes substantial time and CPU. section 3.5
The Spring TestContext Framework checks its cache whenever a test needs an application context. A cache miss starts the application and stores it; a hit reuses the existing configured instance. Compatibility is based broadly on test configuration, including properties, profiles, configuration classes, and loaded beans. section 3.5.1
Two tests, one application startup
Two ordered inner test classes use identical @SpringBootTest configuration. The first test starts the application; the second reuses it, so a deliberately slow bean is configured once rather than once per class. Enable `logging.level.org.springframework.test=DEBUG` to inspect cache size, hits, misses, and failures.
Use caching deliberately around shared state and destructive tests:
- Prefer tests whose state is initialized locally, or reset shared application state before or after each test. section 3.5.3
- Apply @DirtiesContext to a test method or class when a test damages the application and rebuilding it is the safest recovery. section 3.5.3
- Treat @DirtiesContext as a last resort: it removes the application from the cache but does not clear external state such as database data. section 3.5.3
- Remember that the cache is static and process-local: parallel tests in one process share it, while separate processes do not. section 3.5.3
