@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

