Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

In tests, two cached Spring contexts exist in one JVM and a singleton cache bean seems to hold different data depending on the test class. Explain.

Each application context has its own singletons, and the Spring TestContext framework keeps one cached context for each distinct test configuration, so test classes with different configurations see different instances of the cache bean, each filled by different tests. If the bean also keeps data in a static field, that data is shared by every context in the JVM and leaks between them. We fix it by reducing the number of context variants and removing static state.

Why this question is asked

This puzzle appears in almost every large Spring Boot test suite: a test passes alone and fails in the full run, or a cache seems to contain values that the current test never put there. Interviewers ask it because the explanation needs two pieces of knowledge at once: that singletons are per context, not per JVM, and how Spring's test framework caches contexts. In this answer, we will recap how test contexts are cached, reproduce the problem with two test classes, look at the role of static fields, and then go through the fixes.

1A Quick Recap of Test Context Caching

Starting a Spring Boot application context can take several seconds. If every test class started its own, a suite of 400 classes would spend most of its time starting contexts. So the Spring TestContext framework, which runs behind @SpringBootTest and the test slice annotations, caches contexts in a static map for the life of the JVM, and reuses a context whenever a test class needs the same configuration as an earlier one.

The cache key is the merged configuration of the test: the configuration classes, active profiles, test property sources and properties, context initialisers and customisers. Mock bean definitions such as @MockitoBean are part of the key too, because they change which beans exist. Two test classes that differ in any of these get two separate contexts, both kept alive in the cache. The default maximum is 32 contexts, after which the least recently used one is closed; it can be changed with the spring.test.context.cache.maxSize property.

2Reproducing the Problem

Here are two test classes that look almost the same. The second one adds a mock, which is enough to make its context different.

Java
@Component
class RateCache {
private final Map<String, BigDecimal> rates = new ConcurrentHashMap<>();
void put(String k, BigDecimal v) { rates.put(k, v); }
Optional<BigDecimal> get(String k) { return Optional.ofNullable(rates.get(k)); }
}
@SpringBootTest
class PricingTest {
@Autowired RateCache cache;
@Test void storesRate() { cache.put("EUR", new BigDecimal("1.08")); }
@Test void readsRate() { System.out.println(cache.get("EUR")); } // Optional[1.08] if storesRate ran first
}
@SpringBootTest
class InvoiceTest {
@MockitoBean EmailSender email; // changes the cache key -> second context
@Autowired RateCache cache;
@Test void readsRate() { System.out.println(cache.get("EUR")); } // Optional.empty
}
Which context each test class uses
Test classConfigurationContextRateCache instance
PricingTest@SpringBootTestcontext 1cache A (has EUR)
InvoiceTest@SpringBootTest + @MockitoBean EmailSendercontext 2cache B (empty)
TaxTest@SpringBootTestcontext 1 (reused)cache A (sees EUR from PricingTest)
Same class, different contexts, different singletons.

Notice that InvoiceTest sees an empty cache even though PricingTest stored a rate in a bean of the same class. The two test classes are talking to two different RateCache instances, one in each context. If a third test class has the same configuration as PricingTest, it reuses that cached context and sees EUR already present, put there by a test it knows nothing about. That is the "different data depending on the test class" effect.

3How Static Fields Make It Worse

Singletons in separate contexts are at least isolated from each other. Static fields are not. A static field belongs to the class, and the class is loaded once for the whole JVM, so every context shares it. If RateCache kept its map in a static field, or used a static helper cache, the second context would see data from the first, even though Spring created separate instances. The same happens with static holders of the application context, static counters and static caches in utility classes.

So we can see two different symptoms. With instance fields, each context has its own state, and tests that share a context share data. With static fields, every test in the JVM shares data, whichever context it uses. Both make the outcome depend on which tests ran before, which is the definition of a flaky suite.

4Fixing It

The first fix is to make tests independent of earlier tests. A test that needs a known cache state should set it up itself, and shared mutable beans should be cleared in @BeforeEach or @AfterEach, for example with a clear() method on the cache or a test helper that resets all caches. This is better than @DirtiesContext, which closes the context after the test and forces a slow restart for the next one.

The second fix is to reduce the number of context variants. Each extra mock or property combination starts a new context, which is slow and multiplies the places where state lives. A common approach is a small number of shared base test classes or meta-annotations that declare the same mocks and properties, so most tests share a single context. Spring's test logging can show how many contexts were created; when that number is close to the number of test classes, the cache is not helping.

The third fix is to remove static state from application code. Caches belong in beans, and if a library forces a static cache, the test setup must reset it. This change also helps production, where static state causes similar trouble with multiple contexts and class reloading.

Java
@SpringBootTest
abstract class ServiceTestBase { // one shared configuration -> one context
@MockitoBean EmailSender email;
@Autowired RateCache cache;
@BeforeEach void resetState() { cache.clear(); } // each test starts clean
}
class PricingTest extends ServiceTestBase { /* ... */ }
class InvoiceTest extends ServiceTestBase { /* ... */ } // same context, same cache, cleared per test

5Follow-up questions

Why not just put @DirtiesContext on every test class?

It works, but it throws away the benefit of caching. Every class then starts a fresh context, which can turn a three minute suite into a thirty minute one. @DirtiesContext is for the rare test that changes the context in a way we cannot undo, such as modifying a bean definition. For ordinary data, resetting the state is far cheaper.

How can we see how many contexts the suite creates?

Setting the logging level of org.springframework.test.context.cache to DEBUG prints cache statistics, including the number of contexts, hits and misses. If misses are close to the number of test classes, many tests have slightly different configurations, and grouping them under shared base classes or annotations will help both speed and consistency.

Can two cached contexts also interfere through external resources?

Yes. Each context may start its own embedded server on a random port, its own Kafka consumers in the same group, or scheduled jobs against the same test database. Consumers in an older cached context can steal messages meant for the current test. Keeping the number of contexts low and disabling background listeners in tests that do not need them reduces this.

6Conclusion

In this answer, we saw that singletons are per context, and that the Spring TestContext framework caches one context per distinct test configuration, so a single JVM can hold several instances of the same cache bean, each filled by whichever tests used that context. Static fields are shared across all of them and leak data between contexts. The cure is tests that set up and reset their own state, fewer context variants through shared base classes, and no static state.

What to say in the interviewAbout 80 seconds aloud

Open with

The key point is that a Spring singleton is one instance per application context, not per JVM. The Spring test framework caches contexts in a static map, keyed by the test's merged configuration: configuration classes, profiles, properties and mock bean definitions such as @MockitoBean.

Then, if they want more

So if two test classes differ, for example one adds a @MockitoBean, they get two contexts, both cached, and each has its own instance of the cache bean.

Tests that share a context share that instance, so a later test class can see entries put there by an earlier one, while a class with a different configuration sees an empty cache. That is why the data seems to depend on the test class.

If the cache, or something it uses, keeps data in a static field, it is even worse, because static fields are shared by all contexts in the JVM, so data leaks between contexts too.

To fix it, I would make each test set up and reset its own state, for example clearing the cache in @BeforeEach rather than using @DirtiesContext, reduce context variants with shared base classes so most tests use one context, and remove static state from the code.

About this answer

Last updated
12 November 2026
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.
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 "In tests, two cached Spring contexts exist in one JVM and a singleton cache bean seems...": https://scrivio-interview-library.netlify.app/spring-boot/bean-scopes/d41ed55a93/