spring-jpa-testing
Spring JPA Testing
CRITICAL: @DataJpaTest requires TestEntityManager for test data setup and flush()+clear() before read assertions. Tests that skip this read from the Hibernate L1 cache and produce false-passing tests — the query is never executed against the database. See "Critical Rules" below.
Signals: @DataJpaTest, JpaRepository, EntityManager, TestEntityManager, @ServiceConnection, PostgreSQLContainer, @AutoConfigureTestDatabase, @Modifying, clearAutomatically, Testcontainers, Hibernate 6, Hibernate 7
Tested With
- Spring Boot 3.2+ / Spring Boot 4.x
- Spring Framework 6.x / Spring Framework 7.x
- Hibernate 6.x / Hibernate 7.x
- JUnit 5, Testcontainers 1.19+
Critical Rules — Always Apply in @DataJpaTest
1. Use TestEntityManager for test data setup — never Mockito mocks.
@DataJpaTest provides a real in-memory database. Mocking the repository defeats the purpose.
Use @Autowired TestEntityManager em and em.persist() / em.persistAndFlush() to insert test data.
Do NOT use the repository under test for setup — that creates circular logic where a bug in the repository masks both setup and assertion failures.