Video in progress

Strong Middle 🧪 Testing

How does the Spring test context cache work, and why do tests suddenly slow down in a big project?

Spring caches a started context by its configuration key, and test classes with identical settings reuse it. A different @MockitoBean, profile, property or @DirtiesContext creates a new key, and each one starts a context from scratch.

📖 Answer

The key (MergedContextConfiguration) is built from: configuration classes, active profiles, @TestPropertySource and properties, context customizers (mock beans and @DynamicPropertySource go here), and webEnvironment.

By default the cache holds 32 contexts (spring.test.context.cache.maxSize) and evicts the oldest by LRU. Each cached context comes with its own connection pool, threads and possibly a container connection. So enlarging the cache isn't a fix either: CI runs out of memory or the number of database connections hits the limit.

The slowdown is usually gradual: someone adds @TestPropertySource(properties = "feature.x=true") to one test, someone else @ActiveProfiles("kafka"), a third a new @MockitoBean. In a year 4 contexts become 20.

How I find it:

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

The log prints cache hit/miss statistics. Or I just count the "Started ... in" lines.

The cure:

  • a shared AbstractIntegrationTest with one set of mocks and one profile;
  • switch feature flags through a bean inside the test rather than through properties;
  • hunt down @DirtiesContext and justify each one: it removes the context from the cache entirely;
  • clean state without changing the context (truncate the database, reset the mocks).