Skip to content
Latchkey

Spring Boot @DirtiesContext rebuilding the context in CI

@DirtiesContext tells Spring to close and discard the cached context so the next test builds a new one. Overusing it means CI rebuilds the whole application repeatedly, wasting time and heap.

What this error means

CI test time balloons and memory climbs; logs show the application context starting many times, correlating with classes or methods annotated @DirtiesContext.

Spring Boot
Started ExampleApplication in 5.91 seconds  # after @DirtiesContext
Started ExampleApplication in 6.03 seconds  # rebuilt again
... eventually: java.lang.OutOfMemoryError: Java heap space

Common causes

@DirtiesContext used where state is not mutated

The annotation is applied defensively even though the test does not actually change the context, forcing needless rebuilds.

Class-level DirtiesContext on many classes

Marking whole classes dirty discards the cache repeatedly across the suite.

How to fix it

Remove unnecessary @DirtiesContext

  1. Identify tests that do not mutate shared context state.
  2. Drop @DirtiesContext from them so the cached context is reused.
  3. Reset only the specific state you change (a @MockBean, a table) instead.

Scope dirtying to the smallest unit

If you must dirty, limit it to the method and phase that truly needs a fresh context.

src/test/java
@DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD)

How to prevent it

  • Use @DirtiesContext only when a test genuinely corrupts the context.
  • Reset targeted state (mocks, DB rows) rather than the whole context.
  • Keep configurations uniform so the context cache stays warm.

Frequently asked questions

What causes "@DirtiesContext rebuilding contexts"?
The annotation is applied defensively even though the test does not actually change the context, forcing needless rebuilds.
How do I fix @DirtiesContext rebuilding contexts?
Remove unnecessary @DirtiesContext

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card