Video in progress
What settings does @DataJpaTest run with by default, and what traps does that lead to?
By default it replaces the real DataSource with an embedded database, makes each test @Transactional with a rollback at the end, and turns on SQL logging. As a result, many bugs stay hidden because of H2 dialect differences and because nothing gets flushed.
📖 Answer
The first trap is the embedded database. If H2 is on the classpath, @DataJpaTest starts H2 instead of PostgreSQL. jsonb, ON CONFLICT, partial indexes and Postgres-specific functions are missing in H2 or behave differently. The tests are green and the query fails in prod. To work with the real database:
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
class OrderRepositoryTest {
@Container @ServiceConnection
static PostgreSQLContainer<?> pg = new PostgreSQLContainer<>("postgres:16-alpine");
}
The second trap is rollback and flush. The test transaction rolls back at the end, so Hibernate often never sends the INSERT to the database at all. Unique constraint violations and NOT NULL column errors go unseen.
repo.save(new User("ali@mail.uz"));
repo.save(new User("ali@mail.uz")); // violates unique, but there's no error yet
em.flush(); // the error shows up right here
If you use TestEntityManager.flush() and clear(), the next find reads from the database instead of the first-level cache, and that's where you also see mapping errors.
The third is that only the JPA layer is loaded, with no @Service beans. That isn't a bug, but people who don't know it are surprised by the "bean not found" error.
Sign up to mark studied questions and save your progress.