@DirtiesContext marks a Spring application context as modified after a test changes shared state. The Spring TestContext Framework then discards the context and recreates it for later tests, preventing data left by one test from affecting another. section 20.4
Recreate the context after every test
@SpringBootTest @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) class SaveRetrieveUserTest { @Autowired private UserRepository userRepository; @RepeatedTest(2) void saveRetrieve() { // save and retrieve a user } } With AFTER_EACH_TEST_METHOD, the context and its cache are removed after each method. The next execution receives a newly initialized application and database state, so repeated tests do not encounter the previous record.
Apply the annotation at the scope and lifecycle point that matches the contamination risk:
- Annotate either a test method or a test class. section 20.4
- Choose recreation before or after each test method, or before or after the test class. section 20.4
- Use it sparingly: recreating tables and reinitializing the application adds a cost tied to context reinitialization, including in CI/CD execution. section 20.4 section 20.5
- Compare it with @Transactional when rollback can isolate test data; separate transactions can commit records and make later tests fail. section 20.5
