Skip to content
javahacks.dev
Testing

How to Cache the Spring Test Context to Speed Up Tests

Understand Spring test context caching: what the cache key contains, how to see hits and misses, limit the cache size and design tests to share contexts.

6 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the OpenJDK, Spring Boot and GitHub Actions logos.

Spring's test framework builds an ApplicationContext for the first test that needs it and keeps it for later tests with the same needs. This cache is the main reason Spring Boot suites are not far slower than they are. Understanding it lets you keep it effective.

What the cache does

A static ContextCache maps a MergedContextConfiguration to a loaded context. When a test class starts, Spring computes the key from the annotations on the class. If the key exists, the context is reused, and beans keep their state. If not, Spring creates the context and stores it. All tests in one JVM share the cache. Surefire or Gradle forks each have their own.

What is in the key

Everything that changes how the context is built:

Part of the keyChanged by
Configuration classes@SpringBootTest(classes=...), @ContextConfiguration, @Import
Active profiles@ActiveProfiles
Property sources@TestPropertySource, properties = ...
Dynamic properties@DynamicPropertySource (counted by method)
Mock beans@MockitoBean, @MockitoSpyBean, legacy @MockBean
Initialisers and customisersContextCustomizer implementations
Web environmentwebEnvironment of @SpringBootTest
Parent context@ContextHierarchy

Changing any one of these gives a different key and a separate context.

See the cache work

properties
logging.level.org.springframework.test.context.cache=DEBUG

The log shows statistics such as:

Text
Spring test ApplicationContext cache statistics: [DefaultContextCache@5a4b size = 3, maxSize = 32, parentContextCount = 0, hitCount = 41, missCount = 3]

missCount = 3 means three contexts were built; hitCount = 41 shows how many tests reused one. A high miss count relative to the number of test classes is the signal to act. Count the classes with different annotations to find the cause.

Design for sharing

Create a shared annotation, as in custom test annotations:

java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SpringBootTest
@ActiveProfiles("test")
@Import(TestInfrastructure.class)
public @interface IntegrationTest { }

Then move per-class mocks away from the class level. A test needing a mocked client can configure one shared mock bean defined in TestInfrastructure, and reset it with Mockito.reset in @BeforeEach. The shared mock bean is part of every context key, so they stay equal.

For @DynamicPropertySource with containers, define it in a common base so the key matches. The @ServiceConnection approach in Testcontainers support avoids dynamic property variance.

Size and eviction

properties
spring.test.context.cache.maxSize=64

The default maximum is 32. When it is full, the least recently used context is closed and removed. Raising it keeps more variants alive, at the cost of memory and the resources each context holds (connection pools, threads). A cache that is evicting means you have more distinct configurations than you should, so consider reducing variants first.

DirtiesContext and its effect

@DirtiesContext removes the context from the cache after the test or class, so the next test rebuilds it. Use it rarely, as covered in keeping SpringBootTest fast. Instead of dirtying, reset the specific state.

Beans keep state across tests

A shared context means singleton beans, caches and in-memory fakes keep their state between test classes. Tests must clean up:

  • clear caches and reset counters in @BeforeEach;
  • truncate tables or roll back with @Transactional tests;
  • reset mocks (Spring's MockitoBean resets mocks after each test by default).

Order-dependent failures that only appear in the full run usually come from leaked state in a shared context, not from the cache itself.

Slices have their own contexts

Each slice type and each set of beans is a separate key. A @WebMvcTest for OrderController and another for CustomerController build different contexts, because the controllers loaded differ. A @WebMvcTest without a controller class, loading all controllers, can be shared across all controller tests, at the cost of a bigger context. Weigh startup against sharing, see test slices.

Verify the improvement

Run the suite and record total time, number of context misses and slowest classes (the Gradle test report or Surefire output). Make one change at a time. The combination of fewer contexts and no DirtiesContext normally gives the biggest drop.

A suite that builds six contexts when it needs one

Here is how a cache is quietly defeated. Three test classes in the same module, each reasonable on its own:

java
@SpringBootTest
@MockitoBean(types = PaymentGateway.class)
class OrderServiceTest { /* ... */ }

@SpringBootTest
@MockitoBean(types = EmailSender.class)
class NotificationTest { /* ... */ }

@SpringBootTest
@ActiveProfiles("test")
class ReportingTest { /* ... */ }

The three classes have three different keys: one has a mock of PaymentGateway, one a mock of EmailSender, one an active profile. That is three full application startups, and in a project with 40 integration test classes written by different people, it becomes 15 or 20 contexts without anyone deciding it. The log line missCount makes it visible, and the fix is to agree on one configuration.

One base configuration, mocks defined once

Put the shared annotations on one meta-annotation or base class, and declare every mock the suite needs there, even if a given test does not use it:

java
@SpringBootTest
@ActiveProfiles("test")
@MockitoBean(types = {PaymentGateway.class, EmailSender.class})
@Import(TestClock.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface IntegrationTest {
}
java
@IntegrationTest
class OrderServiceTest {

    @Autowired PaymentGateway payments;
    @Autowired OrderService orders;

    @BeforeEach
    void resetMocks() {
        Mockito.reset(payments);
    }

    @Test
    void chargesOnce() {
        when(payments.charge(any())).thenReturn(Receipt.ok("r-1"));
        orders.place(new NewOrder("sku-1", 2));
        verify(payments, times(1)).charge(any());
    }
}

All three classes now share one key. The price is that a mock exists in the context of tests that do not touch it, which costs nothing, and that each test must reset the mocks it uses, because the beans are shared. Make that reset a habit with an extension that does it for every test, so nobody has to remember it.

Check how many contexts you actually build

Run the suite once with the cache logging on and count the misses:

Shell
./mvnw test -Dlogging.level.org.springframework.test.context.cache=DEBUG \
  | grep "Spring test ApplicationContext cache statistics" | tail -1

The final statistics line holds the total. A suite of 40 classes with missCount = 2 or 3 is healthy: one full context, one or two slices. If the number is near the class count, the cache is not helping, and the table of key parts above tells you where to look. Search for @MockitoBean, @ActiveProfiles, @TestPropertySource and @DynamicPropertySource declared directly on test classes, since those are the usual culprits.

Testcontainers and the cache together

A container started in a static field of a base class starts once per JVM and its connection details are part of the context. Declare it in one place and use @ServiceConnection, which keeps the key stable:

java
@TestConfiguration(proxyBeanMethods = false)
public class TestInfrastructure {

    @Bean
    @ServiceConnection
    PostgreSQLContainer<?> postgres() {
        return new PostgreSQLContainer<>("postgres:17");
    }
}

Then import it from the shared @IntegrationTest annotation with @Import(TestInfrastructure.class). Every test class gets the same context and the same database, and the container starts once for the whole run. Per-class containers with @DynamicPropertySource each create a new key, so avoid them unless a test needs an isolated database.

Keeping shared state clean

A shared context means a shared database, so tests need a cleanup strategy that is not @DirtiesContext. The cheapest is a transaction rolled back by the test:

java
@IntegrationTest
@Transactional
class OrderRepositoryTest {
    @Test
    void savesAndFinds() { /* changes roll back after the test */ }
}

@Transactional on a test rolls back at the end of each method, which restores the database without touching the context. It does not help for tests that go through a real HTTP call on a random port, because the server runs on another thread with its own transaction. For those, delete what the test created in an @AfterEach or truncate the tables with a small helper bean. Either costs far less than rebuilding the application for the next test class.

When this does not apply

Tests that need a fresh context by design, such as testing application startup properties, accept the cost. References: Context caching and Spring Boot test features.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.