Spring TestContext Framework provides testing-context management and integration-testing support independently of a particular testing framework. It fits persistence testing, where application behavior depends on an external database, and works with JUnit 5 and Spring Boot. section 20.0 section 20.3
Detecting and preventing dirty database state
A @SpringBootTest can inject UserRepository, save a User, retrieve all users, and assert the result. Repeating the test exposes state leakage: the first execution leaves its row behind, so the second finds two users. Transactional tests can isolate database changes; @Rollback is the default, while @Commit or @Rollback(false) preserves changes. section 20.3 section 20.9
Core mechanisms support context setup, lifecycle control, and database-test configuration:
- TestContextManager manages one TestContext and dispatches events to registered TestExecutionListener instances. section 20.3
- Default listeners prepare test instances, support dependency injection, and run around JUnit 5 lifecycle methods and test execution. section 20.8
- Custom listeners replace automatic defaults unless MERGE_WITH_DEFAULTS is selected; merging preserves dependency injection and the default listener set. section 20.8
- @ActiveProfiles selects Spring configuration profiles, while @DirtiesContext requests context reinitialization after test changes. section 20.8
Listing 20.5 The SaveRetrieveUserTest class
Path: Ch20/1 spring testing/src/test/java/com/manning/javapersistence /testing/SaveRetrieveUserTest.java @SpringBootTest class SaveRetrieveUserTest { @Autowired private UserRepository userRepository; @Test void saveRetrieve() { userRepository.save(new User("User1")); List<User> users = userRepository.findAll(); assertAll( () -> assertEquals(1, users.size()), () -> assertEquals("User1", users.get(0).getName()) ); } }
Use the complete save-and-retrieve test as a starting point for persistence integration tests, then add transaction or cleanup controls when repeated execution exposes shared state. section 20.3
