@DirtiesContext tells the Spring TestContext Framework that a test, or a test class, changes the cached ApplicationContext in a way that makes it unsafe to reuse. Spring closes that context and builds a fresh one for the next test that needs it. Use it sparingly: rebuilding a context is slow, and most state problems have cheaper fixes.
Spring caches application contexts across test classes, keyed by their configuration. That cache is what keeps large suites fast, and @DirtiesContext is the explicit way to evict an entry from it.
@DirtiesContext@DirtiesContext is the right toolWhen you run @SpringBootTest or @ContextConfiguration tests, the TestContext Framework builds an ApplicationContext once and stores it in a static cache. Every later test class with the same configuration (same classes, properties, active profiles, mock beans and initializers) gets the same instance back. A full Spring Boot context can take several seconds to start, so this sharing is what keeps a suite with hundreds of tests practical.
The side effect is that singleton beans, in-memory caches, embedded databases and anything else held by the context survive from one test to the next. If a test mutates that state and does not undo it, the next test sees the leftovers. @DirtiesContext marks the context as "dirty" so it is closed and removed from the cache.
The cache holds 32 contexts by default and evicts the least recently used one. You can change that with the spring.test.context.cache.maxSize property.
@DirtiesContextThe annotation is org.springframework.test.annotation.DirtiesContext. You can put it on a test class or on a test method.
In this example CounterService is a singleton that keeps a counter in a field. The second test changes that field, so it is annotated: after the method finishes, Spring discards the context and the next test gets a new CounterService that starts at zero again.
With JUnit 5 you do not need @RunWith(SpringRunner.class) or @ExtendWith(SpringExtension.class) on Spring Boot tests, because @SpringBootTest already registers the extension. @RunWith belongs to JUnit 4 and does nothing under JUnit Jupiter.
The annotation has three attributes that control when and how much is discarded.
| Attribute | Values | Default | Meaning |
|---|---|---|---|
classMode | BEFORE_CLASS, BEFORE_EACH_TEST_METHOD, AFTER_EACH_TEST_METHOD, AFTER_CLASS | AFTER_CLASS | Used when the annotation is on a class |
methodMode | BEFORE_METHOD, AFTER_METHOD | AFTER_METHOD | Used when the annotation is on a method |
hierarchyMode | EXHAUSTIVE, CURRENT_LEVEL | EXHAUSTIVE | Used with context hierarchies |
A class-level annotation with the default AFTER_CLASS closes the context once every test in the class has run, so other classes never see the changes. Use AFTER_EACH_TEST_METHOD only when every test in the class needs a pristine context, because it rebuilds the context for each method.
AFTER_METHOD is the default for a method: the context is discarded once that method completes. BEFORE_METHOD discards it before the method runs, which helps when the previous test left things dirty and you cannot change it.
If you use @ContextHierarchy, hierarchyMode = EXHAUSTIVE removes the current context and all its parents and children from the cache. CURRENT_LEVEL removes only the current level and its descendants, which keeps an expensive parent context alive.
@DirtiesContext is the right toolReach for it when the context itself is damaged, not merely when data changed:
ConfigurableEnvironment methods, and you cannot reverse it.Because every @DirtiesContext forces a full context startup, try these first:
@Transactional to the test class. Spring rolls back each test's database changes automatically (this does not apply to code running in another thread or a real HTTP server on a random port).@Sql scripts, @BeforeEach and @AfterEach methods, or Testcontainers per-test reset logic.@MockitoBean (Spring Framework 6.2 and Spring Boot 3.4 and later) or @MockBean (older versions, deprecated since Boot 3.4) with @AfterEach resets. Mock beans are reset after each test by default. Note that a different set of mock beans produces a different cache key, so it creates a separate context anyway.reset() method for test use.@DynamicPropertySource to feed container ports into a context that is shared by all tests, rather than rebuilding per test.Also keep configuration identical across test classes where you can. Many @SpringBootTest variants with slightly different properties or mocks multiply the number of cached contexts and slow the suite down more than a single @DirtiesContext would.
@DirtiesContext on every test class "to be safe". This disables the cache benefit and can multiply build times.@RunWith(SpringRunner.class) in a JUnit 5 project. Use @SpringBootTest alone, or @ExtendWith(SpringExtension.class) for plain Spring tests.@DirtiesContext reset the database?No. It closes and rebuilds the Spring context. An embedded database owned by that context, such as H2, is recreated with it, but an external database keeps its data. Use @Transactional, @Sql or container resets for data.
@DirtiesContext inherited by subclasses?Yes. The annotation is @Inherited, and its classMode applies to subclasses as well, so a base test class can set it once.
Each use costs a full context startup for the next test that needs it, which can range from under a second for a small context to many seconds for a large Spring Boot application. Measure your suite before and after.
@WebMvcTest or @DataJpaTest?Yes. It works with any TestContext-based test, but those slice tests already create small contexts, so you rarely need it.
@DirtiesContext marks the cached Spring test context as unusable so the next test gets a fresh one. Choose classMode or methodMode to limit how often it fires, prefer @Transactional, @Sql and stateless beans where they are enough, and keep it for cases where a test genuinely damages the context.