Sub topic 14
How the test context cache works
This chapter assumes you can write @SpringBootTest and slice tests, that you know what a Spring bean is, and that you have run a Gradle or Maven test build. It explains why a suite of Spring tests can be fast or slow with the same number of tests, and how to keep it fast.
Why a cache exists
Starting a Spring ApplicationContext is the most expensive thing a Spring test does. Spring scans classes, builds bean definitions, applies auto-configuration, and may open database connections. A full context often takes several seconds. A mock-based unit test takes milliseconds.
If every test class built its own context, a suite with 100 integration test classes would pay that startup cost 100 times. The Spring TestContext Framework avoids this. It stores each context it builds in a cache, and later test classes that need an identical context reuse it.
The cache lives in memory, for the lifetime of the test JVM. It is not shared between JVMs, so parallel forks or separate Gradle test workers each build their own contexts.
The cache key: the merged context configuration
Spring decides whether two test classes can share a context by comparing a cache key. The key is built from the test's merged context configuration. It includes:
- the configuration classes (
@SpringBootTest(classes = ...),@Import, nested@TestConfiguration) - active profiles (
@ActiveProfiles) - inline properties (
@SpringBootTest(properties = ...)) and@TestPropertySourcelocations - property source and initializer settings (
@ContextConfigurationinitializers) - context customizers, such as the ones that record
@MockitoBeanor@MockBeandefinitions - the web environment (
webEnvironment) for Spring Boot tests - the context loader and parent context, if any
If two test classes produce equal keys, they share one context. If any element differs, Spring builds a second context and caches that too.
Slice annotations take part in this. @WebMvcTest(GreetingController.class) and @WebMvcTest(OtherController.class) have different controller lists, so they have different keys. Each slice also adds its own type-exclude filters and auto-configuration imports, so a @WebMvcTest context never matches a @DataJpaTest context.
Seeing the cache work
Spring logs cache activity at DEBUG level under the org.springframework.test.context.cache logger. Add this to src/test/resources/application.properties to watch it:
logging.level.org.springframework.test.context.cache=DEBUGEach lookup logs a line with statistics such as size, hits, misses, parentContextCount. A miss means Spring had to build a new context. A hit means it reused one. After a full run, a high miss count relative to the number of test classes shows that the suite is fragmenting.
What fragments the cache
The common causes are small, accidental differences between test classes. Look at these first.
Different `@MockitoBean` sets
Mock bean definitions are part of the key. These two classes get different contexts, because they mock different things:
@SpringBootTest
class OrderServiceTest {
@MockitoBean
PaymentClient paymentClient;
// tests...
}
@SpringBootTest
class ShippingServiceTest {
@MockitoBean
ShippingClient shippingClient;
// tests...
}This is the most common cause of a slow suite. Each new combination of mocks costs one full context startup. @MockitoBean is available from Spring Framework 6.2 (Spring Boot 3.4). In earlier versions, @MockBean behaves the same way for caching purposes.
Different properties or profiles
@SpringBootTest(properties = "feature.x=true") in one class and no properties in another gives two keys. The same applies to @ActiveProfiles("test") versus @ActiveProfiles({"test", "slow"}). Even the order or set of profiles matters when it changes the merged result.
Different web environments
webEnvironment = MOCK (the default) and webEnvironment = RANDOM_PORT produce different keys. Mixing them in one suite means at least two contexts, and a running server context is heavier than a mock one.
Different `@TestConfiguration` imports
A @TestConfiguration class that is a nested static class is picked up only by its enclosing test class, so that class gets its own key. If several test classes need the same extra beans, put the configuration in a top-level class and @Import it from each of them. Then the key is identical.
@TestConfiguration(proxyBeanMethods = false)
public class FixedClockConfig {
@Bean
Clock clock() {
return Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC);
}
}@SpringBootTest
@Import(FixedClockConfig.class)
class InvoiceServiceTest {
// uses the fixed clock
}
@SpringBootTest
@Import(FixedClockConfig.class)
class ReminderServiceTest {
// same key as InvoiceServiceTest, so the context is reused
}Sharing a configuration with a base class
To make several classes share one key deliberately, give them the same annotations. A common way is an abstract base class that holds the configuration and the mocks:
@SpringBootTest
@ActiveProfiles("test")
@Import(FixedClockConfig.class)
abstract class IntegrationTestBase {
@MockitoBean
PaymentClient paymentClient;
}class OrderFlowTest extends IntegrationTestBase {
@Autowired
OrderService orderService;
// tests...
}Subclasses inherit the configuration annotations and the @MockitoBean fields, so every subclass has the same key. The trade-off is that every subclass now gets a mock PaymentClient, whether it needs one or not. A subclass that needs the real client will force a different context. Keep base classes small, and do not grow one into a catch-all that holds every mock the project has.
Dirty contexts and `@DirtiesContext`
A cached context is shared, so a test that changes a singleton bean's state can affect later tests. Examples are a test that writes to an in-memory cache bean, changes a mutable singleton, or registers a bean at runtime.
@DirtiesContext tells Spring to remove the context from the cache after the test. The next test that needs that key builds a new context.
@SpringBootTest
class CacheWarmupTest {
@Autowired
PriceCache priceCache;
@Test
@DirtiesContext
void clearsEntriesOnReset() {
priceCache.put("A", 10);
priceCache.reset();
assertThat(priceCache.size()).isZero();
}
}By default the annotation applies after the method (methodMode = AFTER_METHOD) or after the class when placed on a class (classMode = AFTER_CLASS). Use BEFORE_EACH_TEST_METHOD or BEFORE_CLASS only when you need a fresh context before a test.
Prefer to reset state explicitly. Slice tests such as @DataJpaTest roll back their transaction after each test by default, so they rarely need @DirtiesContext.
Cache size and eviction
The cache is bounded. The default maximum is 32 contexts. When the limit is exceeded, Spring evicts the least recently used context, closes it, and builds it again if a later test needs it. If your suite has more than 32 distinct keys, raise the limit with a JVM system property or a spring.properties file on the test classpath:
spring.test.context.cache.maxSize=64Raising the limit uses more memory, because each cached context holds all its beans. A suite with a high number of contexts is usually better fixed by reducing the number of keys than by raising the limit.
Non-obvious effects of caching
Contexts stay running
A cached context is not closed after its test class finishes. Its beans, thread pools, scheduled tasks, and message listeners keep running until the JVM exits, when a shutdown hook closes the contexts. A scheduled job or listener in a cached context can fire while another test runs. Disable it with a profile or property for the test, or make it conditional.
Testcontainers and the cache
A static @Container field is started and stopped by the Testcontainers JUnit extension for each test class. A context cached from an earlier class may hold a DataSource pointing at a container that has since stopped. If a later class with the same key reuses that context, connections fail.
You can avoid this in two ways. Declare the container as a singleton that outlives the test classes, for example in a shared configuration class with @ServiceConnection, so every context points at the same live container:
@TestConfiguration(proxyBeanMethods = false)
public class ContainersConfig {
@Bean
@ServiceConnection
PostgreSQLContainer<?> postgres() {
return new PostgreSQLContainer<>("postgres:16");
}
}@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Import(ContainersConfig.class)
class GreetingRepositoryTest {
@Autowired
GreetingRepository repository;
@Test
void savesGreeting() {
repository.save(new Greeting("Ada", "Hello, Ada"));
assertThat(repository.findByName("Ada")).isPresent();
}
}Here the container is a bean in the context, so Spring Boot starts it with the context and stops it when the context closes. The container and the context have the same lifetime, which removes the mismatch. Alternatively, give each class its own key so contexts are never reused across containers.
Mutable test data in shared databases
All classes with the same key share the same database. Rows left behind by one test remain visible to the next. Roll back with @Transactional where possible, or clean up in @AfterEach. Note that @Transactional does not roll back work done on another thread, such as a request handled by a real server in RANDOM_PORT tests.
A procedure for tuning a slow suite
- Turn on the cache
DEBUGlogging and run the whole suite once. - Count context creations. The number of
misslines is the number of contexts built. - List the keys. Group test classes by their annotations: profiles, properties, mock beans, imports, web environment.
- Remove differences that are not needed. Move shared mocks to a base class or use a shared
@TestConfiguration. - Replace
@MockitoBeanin a class with a hand-written stub registered in a shared configuration, when many classes need a same fake. - Push logic down. Cover business rules with plain unit tests, which need no context at all, and keep full-context tests for wiring.
- Run again and compare the miss count and the total time.
Summary table
| Difference between two test classes | Same context? |
|---|---|
| Identical annotations, no mocks | Yes |
| Different `@MockitoBean` fields | No |
| Different `@ActiveProfiles` | No |
| Different `properties` in `@SpringBootTest` | No |
| `MOCK` vs `RANDOM_PORT` | No |
| Same `@Import` of a top-level `@TestConfiguration` | Yes |
| Nested `@TestConfiguration` in each class | No |
| `@WebMvcTest` vs `@DataJpaTest` | No |
| Different test method names or bodies | Yes |
How the lookup works
Exercise
A suite has 12 @SpringBootTest classes. Six use @MockitoBean PaymentClient, and the other six use @MockitoBean ShippingClient. All other annotations are identical. How many application contexts are built, and how would you reduce the count to one?
Show answer
Two contexts are built, one per distinct set of mock beans. To get to one, make both mocks part of the same configuration, for example by moving both @MockitoBean fields into a shared abstract base class that all 12 classes extend. All 12 then have the same key. The cost is that each class gets mocks it may not use, so check that none of the classes need the real PaymentClient or ShippingClient.
Exercise
A repository test with a static @Container field passes alone but fails with connection errors when run after another test class with the same key. Why, and what is one fix?
Show answer
The first class's container stops after that class finishes, but its context stays in the cache with a DataSource pointing at the stopped container. The second class reuses the cached context and cannot connect. One fix is to declare the container as a @ServiceConnection bean in a shared @TestConfiguration and @Import it, so the container starts and stops together with the context.