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.
Started ExampleApplication in 5.91 seconds # after @DirtiesContext
Started ExampleApplication in 6.03 seconds # rebuilt again
... eventually: java.lang.OutOfMemoryError: Java heap spaceCommon 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
- Identify tests that do not mutate shared context state.
- Drop
@DirtiesContextfrom them so the cached context is reused. - 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.
@DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD)How to prevent it
- Use
@DirtiesContextonly 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.