liveBook · Manning

Application context caching

As explained in Testing Spring Boot Applications

A context cache stores configured, running test application contexts for reuse by compatible tests.

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

How Testing Spring Boot Applications covers it

How deep it goes
Explains cache lookup, configuration-based keys, diagnostics, eviction, process scope, and state-related limitations.
Examples
Uses a slow bean, paired @SpringBootTest classes, debug cache statistics, and a destructive test annotated with @DirtiesContext.
What it assumes
Assumes familiarity with Spring Boot tests, application contexts, test configuration, and shared application state.
What you can do after
Diagnose cache hits and misses, structure compatible tests, and selectively force context recreation when isolation requires it.
How it connects
Connects ApplicationContext with Spring TestContext Framework, Spring Boot testing, test isolation, shared state, and @DirtiesContext.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Testing Spring Boot Applications. The section links point to the parts of the book it draws on.