liveBook · Manning

@dirtiescontext

As explained in Testing Spring Boot Applications

@DirtiesContext is a Spring testing annotation that marks an application context as dirty so it is removed from the test context cache and recreated when needed.

@DirtiesContext marks a Spring test application context as dirty, removing it from the context cache so Spring recreates it when needed. Apply it to a test class or method when a test changes or breaks application state that other tests cannot safely reuse. section 3.5.3

Use it selectively because it changes the test application's lifecycle:

  • Annotating a method removes the running application from the cache after that method completes. section 3.5.3
  • Other options can recreate the application before a method or apply lifecycle behavior at class level. section 3.5.3
  • Recreation resets the application itself, but does not clear external state such as database data; clean that state separately. section 3.5.3
  • Prefer locally initialized state or explicit reset logic when possible, keeping context eviction as a last resort because it slows tests. section 3.5.3

Recreate the test application after destructive work

@Test @DirtiesContext void breakStuff() { // ... some destructive test code ... } After breakStuff completes, the application is evicted from the cache and a fresh test application is created when required. section 3.5.3

How Testing Spring Boot Applications covers it

How deep it goes
Explains method and class scope, recreation timing, external-state limits, and performance tradeoffs without detailing annotation internals.
Examples
Uses a destructive breakStuff test annotated to recreate the test application after completion.
What it assumes
Assumes familiarity with Spring test application contexts, context caching, and the need to reset shared test state.
What you can do after
Apply @DirtiesContext to destructive tests and combine it with manual cleanup for state outside the application context.
How it connects
Connects application context caching with test isolation, cleanup logic, database state, and Spring TestContext Framework customization.

Also explained in

Compare how 2 books explain @dirtiescontext →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Testing Spring Boot Applications. The section links point to the parts of the book it draws on.