liveBook · Manning

Test pollution

As explained in Testing Spring Boot Applications

Test pollution is a condition in which tests affect shared state so that their outcomes depend on execution order or prior test activity.

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

How Testing Spring Boot Applications covers it

How deep it goes
Explains shared application and external state, cleanup strategies, and @DirtiesContext costs; stops short of detailed reset implementation.
Examples
Uses inserted database data, deleted in-memory data, destructive tests, and a Docker-hosted database to illustrate pollution.
What it assumes
Contrasts integration tests with unit tests that control inputs and dependencies through manual wiring, stubs, and mocks.
What you can do after
Diagnose/debug with it by isolating setup, cleaning global state, or recreating the Spring test context.
How it connects
Connects test pollution with integration tests, unit tests, shared state, test isolation, and @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.