Test pollution occurs when tests change shared state, making later outcomes depend on execution order or earlier activity. Reused application contexts can retain in-memory data and references to databases, message brokers, or filesystems. section 3.5.3 section 1.2
Reduce pollution by choosing an isolation strategy that matches the state being changed:
- Initialize all required state inside each test method and avoid relying on data left by other tests. section 3.5.3
- Reset shared state before or after each test, such as deleting every repository entry or using unique test data. section 3.5.3 section 1.2
- Use @DirtiesContext when a test damages application components that are difficult to restore, while cleaning external state separately. section 3.5.3
Recreate the test application after destructive work
@Test @DirtiesContext void breakStuff() { // ... some destructive test code ... } @DirtiesContext removes the running application from the context cache after the test, forcing a new test application when needed. It does not clear database or other external state, and therefore remains a slower last-resort option. section 3.5.3
Listing 3.19 Recreating the test app after a test
@Test
@DirtiesContext
void breakStuff() {
// ... some destructive test code ...
}
Use the listing to inspect the minimal annotation pattern for recreating a Spring test application after a destructive test. section 3.5.3
