Video in progress
Everything passes in a `@DataJpaTest` or `@Transactional` test, but on prod the same code fails with a constraint error. What could the cause be?
The test transaction is rolled back at the end, so a flush often never happens at all: the INSERT/UPDATE never reaches the database, and constraint, trigger and FK errors don't show up. Also, reads inside the test come from the persistence context, not the database. The fix is to flush() and clear() in the test, or to write the test without a transaction.
📖 Answer
A classic test:
@DataJpaTest
class UserRepoTest {
@Autowired UserRepository repo;
@Test
void savesUser() {
repo.save(new User("a@b.uz"));
User u = repo.save(new User("a@b.uz")); // the unique email is violated
assertThat(repo.findById(u.getId())).isPresent(); // passed?!
}
}
Both save() calls only do persist() (with a SEQUENCE id), and the INSERTs sit in the queue. findById() sends no SQL, because the object is in the context. The test ends, the transaction rolls back, and the flush never happens at all, which means the constraint is never checked. The interesting part: if you write the assertion with findAll(), the JPQL query triggers a flush because of FlushMode.AUTO and may expose the error. So the test result depends on which method you call, and that isn't a reliable test. With an IDENTITY id, the INSERT goes out immediately and the picture is different again.
A reliable test:
@Autowired TestEntityManager tem;
@Test
void rejectsDuplicateEmail() {
repo.save(new User("a@b.uz"));
repo.save(new User("a@b.uz"));
assertThatThrownBy(() -> tem.flush())
.isInstanceOf(PersistenceException.class);
}
@Test
void mappingRoundTrip() {
Long id = repo.save(new User("x@y.uz")).getId();
tem.flush();
tem.clear(); // the next read is a real SELECT
assertThat(repo.findById(id)).isPresent();
}
Two more sources: H2's differences from PostgreSQL (constraints, types, SQL syntax), which is why you use a real database in Testcontainers; and lazy loading: because the test transaction is open, LazyInitializationException doesn't show up in the test, but it does on prod.
I often write service-level integration tests without @Transactional and clean the data up after each test, so the transaction boundaries match prod.
Sign up to mark studied questions and save your progress.