liveBook · Manning

@dirtiescontext

As explained in Java Persistence with Spring Data and Hibernate epub

@DirtiesContext is a Spring testing annotation that marks an application context as modified so it can be discarded and recreated for subsequent tests.

@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

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains method and class scope plus four lifecycle timings, but defers implementation internals beyond context recreation and caching.
Examples
Uses a repeated SaveRetrieveUserTest, recreated tables, inserted users, Spring Boot startup banners, and transaction-isolation comparisons.
What it assumes
Assumes basic Spring Boot persistence testing and test lifecycle knowledge while teaching context invalidation and recreation.
What you can do after
Operate/configure Spring tests with scoped context recreation and recognize its isolation and execution-time tradeoff.
How it connects
Connects Spring TestContext Framework, @Transactional, persistence testing, database initialization, and continuous integration.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.