Video in progress
What does @DataJpaTest load, what doesn't it load, and what are its traps?
It loads only the JPA layer: entities, repositories, EntityManager, Flyway/Liquibase. Services and controllers aren't included. Each test runs in a transaction that's rolled back at the end, and by default an embedded database replaces the real one.
📖 Answer
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // don't swap in an embedded DB
@Testcontainers
class ProductRepositoryTest {
@Container @ServiceConnection
static PostgreSQLContainer<?> pg = new PostgreSQLContainer<>("postgres:16-alpine");
@Autowired ProductRepository repo;
@Autowired TestEntityManager em;
@Test
void cheapestFirst() {
em.persist(new Product("A", new BigDecimal("50")));
em.persist(new Product("B", new BigDecimal("10")));
em.flush(); em.clear(); // so the next query reads from the DB, not the cache
assertThat(repo.findTop1ByOrderByPriceAsc().getName()).isEqualTo("B");
}
}
In interviews people usually slip up on these three:
- No flush. The test is rolled back at the end, and the INSERT/UPDATE may never reach the database. A unique constraint or trigger error stays hidden in the test — call
em.flush(). - First-level cache. If you
persistand then immediatelyfind, Hibernate hands you the object from memory, which hides mapping errors. Callclear(). - Embedded replacement. Up to Boot 3.4,
Replace.ANYwas the default; if you use Testcontainers, turn it off.
Sign up to mark studied questions and save your progress.