Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Spring @DirtiesContext: evict only a context a test truly changed

Last updated: 5 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

Marking a context dirty closes and removes it from the test cache; use it for mutated container state, not ordinary database cleanup.

What the annotation resets

A test replaces a singleton bean definition or changes a mutable configuration object that survives across test methods. @DirtiesContext tells the TestContext framework to remove that ApplicationContext from its static cache and close it. A later test with the same configuration gets a rebuilt context. This can prevent state leakage, but it does not erase an external database or queue. Cache reuse is valuable only when contexts remain equivalent.

Pick the narrow point

Apply the annotation to the method that dirtied the context when one test is responsible, or to a class when the whole class needs a fresh container. Before using it, ask whether the mutable singleton should instead be reset in an after-test hook or replaced with an immutable test collaborator. Database rows belong to transaction rollback, truncation or disposable-schema ownership, not context eviction. A shared Testcontainer can outlive multiple contexts.

Measure suite cost

Count context starts before and after the annotation and inspect which test class caused eviction. A full Boot context may start migrations, caches, clients and listeners again, so one broad class annotation can cost seconds repeatedly. In a parallel suite, shared static state can still race even if one context gets evicted. Verify a formerly leaked singleton value is absent in the next test and that external data cleanup is independent.

Implementation contract

Java
@DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD)
@Test
void changesGlobalReceiptPolicyForThisTestOnly() {
    mutableReceiptPolicy.setLimit(47);
    assertThat(receiptService.limit()).isEqualTo(47);
}

Cost and verification

Eviction forces context construction and bean initialization on the next compatible test, often far costlier than clearing an in-memory field. It does not reset external infrastructure.

Common Mistakes

  • Do not use @DirtiesContext as a substitute for database cleanup.
  • Do not annotate every integration test by default.
  • Do not leave mutable static state behind and assume context eviction resets it.

Read next

Spring TestContext cache: keep equivalent tests on one context shape, Spring Testcontainers parallel tests: one database can leak another test's rows, Spring @DynamicPropertySource: bind test resources without stale cached values, Spring Data JPA test: flush and clear before trusting a read, Spring ApplicationContextRunner: check conditional assembly in isolation.

spring
spring-testing
dirtiescontext-cache-eviction
Storage details