Quick revision
The short answer
The Spring TestContext framework keeps started application contexts in a static cache inside the JVM, keyed by each test class's merged configuration. The key includes the configuration classes, active profiles, property sources, context customizers such as bean overrides, and initializers, so test classes with identical keys share one context and any difference creates a new one. The cache holds at most 32 contexts by default, set with spring.test.context.cache.maxSize, and evicts the least recently used; @DirtiesContext removes a context from it and forces a rebuild.
What to remember
In this answer, we saw that the TestContext framework caches application contexts in a static, JVM-wide cache keyed by MergedContextConfiguration, which includes configuration classes, profiles, property sources, initializers and context customizers such as bean overrides. Classes with equal keys share a context and any difference starts a new one. The cache holds 32 contexts by default with least-recently-used eviction, @DirtiesContext removes a context and forces a rebuild, and debug logging of the cache category shows hits and misses.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The Spring TestContext framework keeps started application contexts in a static cache inside the JVM, keyed by each test class's merged configuration. The key includes the configuration classes, active profiles, property sources, context customizers such as bean overrides, and initializers, so test classes with identical keys share one context and any difference creates a new one. The cache holds at most 32 contexts by default, set with spring.test.context.cache.maxSize, and evicts the least recently used; @DirtiesContext removes a context from it and forces a rebuild.
Why this question is asked
Context caching is the single biggest factor in how long a Spring integration test suite takes. Two suites with the same number of tests can differ by ten times in build time depending on how many distinct contexts they create. Interviewers ask about the internals because once we know what the key contains, we can predict which classes share a context and fix slow suites deliberately. In this answer, we will follow a test class through the cache lookup, look at what the key is made of, see the size limit and eviction, look at @DirtiesContext, and learn how to read the cache statistics.
1A Quick Recap of the TestContext Framework
When JUnit runs a test class with the SpringExtension, which @SpringBootTest and every slice add for us, the Spring TestContext framework prepares the test. It works out the class's configuration, gets an application context for it, injects beans into the test instance, and runs listeners for things like transactions.
Getting the context is the expensive part, often seconds. So instead of creating one per class, the framework asks a context loader delegate for it, and the delegate looks in a cache first.
2Building the Key
For each test class, the framework merges everything that affects the context into one object called MergedContextConfiguration. It is built from the class, its superclasses and enclosing classes, and its annotations. Its equals() and hashCode() define the cache key.
| Part of the key | Comes from |
|---|---|
| Configuration classes or locations | @SpringBootTest(classes), @ContextConfiguration |
| Active profiles | @ActiveProfiles |
| Property sources and inline properties | @TestPropertySource, properties attribute |
| Context initializers | initializers attribute |
| Context customizers | @MockitoBean, @DynamicPropertySource, slice filters |
| Context loader and parent | Boot's loader, @ContextHierarchy |
3Looking Up the Cache
The cache is a static map, so it lives as long as the JVM and is shared by every test class that runs in it. If the key is present, the class gets the existing context, already started, and the lookup counts as a hit. If not, the context is loaded, stored under the key, and counted as a miss.
- Merge the class's configuration
MergedContextConfiguration - Key in the cache?YesReuse it, count a hitNoLoad a new context, count a miss
- Cache over maxSize?YesEvict and close the least recently usedNoKeep all
- Run the testsbeans injected from that context
- @DirtiesContext?YesRemove and close the contextNoLeave it cached
5 steps in order. Play them, or step through them one at a time.
Notice that FeatureXTest differs by one property, and that alone costs a full startup. The same happens with a different @MockitoBean set or a different profile. Contexts are only shared within one JVM, so test forks on CI each have their own cache.
4The Size Limit and Eviction
Each cached context holds everything a running application holds: connection pools, thread pools, consumers, caches. To keep memory bounded, the cache has a maximum size, 32 by default, which we can change with the spring.test.context.cache.maxSize property, set as a JVM system property or in a spring.properties file at the root of the test classpath. When a new context would exceed it, the least recently used one is evicted and closed. If a later class needs the evicted configuration again, it is loaded again, another miss.
5Removing a Context With @DirtiesContext
@DirtiesContext tells the framework that a test changed the context in a way that later tests must not see, for example by modifying a singleton bean's state. After the class, or after each method depending on its mode, the context is closed and removed from the cache, so the next class with the same key loads a fresh one. It is the right tool for a real change to the context, but each use costs a full startup, so it is worth replacing with a targeted reset of the state when possible.
6Reading the Cache Statistics
To see what the cache is doing, we enable debug logging for the logging category org.springframework.test.context.cache. The framework then logs statistics as contexts are used.
Here, 240 lookups needed only 4 contexts, which is a healthy suite. A missCount close to the number of test classes, or a size pinned at maxSize, tells us contexts are not being shared or are being evicted.
7Follow-up questions
How can you log cache statistics to see hits and misses?
Set the logging level of org.springframework.test.context.cache to DEBUG, for example in the test application.properties or logback-test.xml. The framework then logs the cache size, maxSize, hit count, miss count and failure count, which shows how many contexts the suite started and how often they were reused.
Do two test classes with different test methods but the same annotations share a context?
Yes. Test methods and fields that are not overrides do not affect the key. Only configuration that changes the context, such as classes, profiles, properties and customizers, does.
Are failed contexts cached?
Since Spring Framework 6.1 the framework records failures per key and, after a threshold that defaults to one attempt, makes later classes with the same key fail immediately instead of retrying the slow startup.
8Conclusion
In this answer, we saw that the TestContext framework caches application contexts in a static, JVM-wide cache keyed by MergedContextConfiguration, which includes configuration classes, profiles, property sources, initializers and context customizers such as bean overrides. Classes with equal keys share a context and any difference starts a new one. The cache holds 32 contexts by default with least-recently-used eviction, @DirtiesContext removes a context and forces a rebuild, and debug logging of the cache category shows hits and misses.
Open with
The TestContext framework keeps a static cache of application contexts inside the JVM. For each test class it builds a MergedContextConfiguration from the class, its superclasses and its annotations, and that object is the cache key.
Then, if they want more
It includes the configuration classes or locations, active profiles, property sources and inline properties, context initializers, and context customizers, which is where @MockitoBean overrides, @DynamicPropertySource and slice filters end up, plus the loader and any parent context.
If another class already produced an equal key, the new class reuses that started context, which is a hit; any difference, even one extra property or mock, means a new context, a miss.
The cache is limited to 32 contexts by default, configurable with spring.test.context.cache.maxSize, and evicts the least recently used one, closing it. @DirtiesContext explicitly closes and removes a context so the next class rebuilds it, which is why it is expensive. To see what is happening, I turn on debug logging for org.springframework.test.context.cache, which prints size, hit count and miss count.
Since the cache is per JVM, parallel forks each have their own cache, so reducing distinct configurations matters even more when tests run in parallel.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Framework 6
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Boot reference, Testing
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "How does the Spring TestContext framework cache application contexts between test...": https://scrivio-interview-library.netlify.app/spring-boot/spring-boot-test/4954722d9c/