Sub topic 14
How the test context cache works
This chapter assumes you can write @SpringBootTest and slice tests, and that you know what a Spring bean and an ApplicationContext are. It explains why some test suites start the application once and others start it dozens of times.
Why the cache exists
Starting a Spring context is the slowest part of most integration tests. It scans classes, builds beans, and may connect to a database. Spring's TestContext framework avoids repeating this work. After it builds a context for a test class, it stores the context in a static cache. Later test classes that need an identical context reuse it, so they start almost instantly.
The cache lives for the whole JVM run of the test task. Test classes share contexts across the suite. Test methods inside one class share it too.
What makes up the cache key
Spring decides whether two test classes can share a context by comparing a merged configuration key. Two classes get the same context only if every part of the key matches. The key includes:
- The configuration classes and
@ContextConfigurationlocations. - Active profiles from
@ActiveProfiles. - Properties from
@TestPropertySourceand@SpringBootTest(properties = ...). - The web environment, such as
MOCKorRANDOM_PORT. - Context customizers. In Spring Boot,
@MockitoBean,@MockBean,@SpyBean,@DynamicPropertySource, and@Importall add customizers.
The last item causes most surprises. A mock bean declared in one test class changes the context definition. A class with a different set of mocks gets a new context, even if everything else is the same.
@SpringBootTest
class OrderServiceTest {
@MockitoBean
PaymentClient paymentClient;
// context A
}
@SpringBootTest
class InvoiceServiceTest {
@MockitoBean
TaxClient taxClient;
// context B: a different mock set means a different key
}
@SpringBootTest
class ShippingServiceTest {
@MockitoBean
PaymentClient paymentClient;
// context A again: same key as OrderServiceTest, so it is reused
}Slice annotations such as @WebMvcTest(GreetingController.class) also produce keys. Each different controller list is a different key, so a suite with many @WebMvcTest classes naming different controllers builds one context per controller.
Seeing the cache at work
The cache logs its hits and misses. Turn on debug logging for the cache class in src/test/resources/application.properties:
logging.level.org.springframework.test.context.cache=DEBUGEach test class then logs a line with the cache size, hit count, and miss count. A miss means a new context was started. If the miss count is close to the number of test classes, the cache is not helping you.
Dirtying the context
A test that changes shared state in the context, such as a singleton bean's fields, can break later tests. @DirtiesContext tells Spring to close the context and remove it from the cache after the class or method.
@SpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class CacheWarmupTest {
// the context is discarded after this class finishes
}Each use forces a rebuild for the next class that needs that context, so it is costly. Prefer other fixes first: reset state in @BeforeEach, use @Transactional tests that roll back, or call Mockito.reset on shared mocks (Spring resets @MockitoBean mocks after each test by default).
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Different `@MockitoBean` sets in each test class | A new context per distinct set | Move shared mocks to a common base class or a shared `@TestConfiguration` |
| Per-class `@ActiveProfiles` or `properties` | Separate contexts | Use one profile and one property set across integration tests |
| `@DirtiesContext` as a default cleanup | Context rebuilt repeatedly | Clean data explicitly instead |
| Many `@WebMvcTest` classes with different controller lists | One context per list | Accept it, or group related controllers |
How the pieces fit
Exercise
Two test classes both use @SpringBootTest. One declares @MockitoBean UserClient userClient. The other has no mock beans and the same configuration otherwise. Do they share a context, and why?
Show answer
No. The mock bean is a context customizer that is part of the cache key. The class with the mock and the class without it have different keys, so Spring starts a second context. To share one, declare the same mocks in both classes, or move the mock to a shared base class.
Exercise
How can you check how many contexts your suite starts?
Show answer
Set logging.level.org.springframework.test.context.cache=DEBUG. The log reports the cache size, hits, and misses after each test class. Each miss is one context startup.