Video in progress
What bugs can stay hidden when you put @Transactional on an integration test?
The test and the service run in one transaction that rolls back at the end. So lazy loading errors, constraint violations at commit time, and the service's own transaction boundaries all stay invisible, and then show up in prod.
📖 Answer
The classic case:
@SpringBootTest
@Transactional
class OrderIT {
@Test
void buyurtma_qatorlari_qaytadi() {
OrderDto dto = orderService.getOrder(id); // order.getItems() is lazy inside
assertEquals(3, dto.items().size()); // the test passes
}
}
The test transaction is open, the Hibernate session is alive, and the lazy collection loads without a problem. In prod, the session closes as soon as getOrder returns, and the controller throws a LazyInitializationException.
Other hidden problems:
@Transactional(propagation = REQUIRES_NEW)or async code runs in a separate transaction and doesn't see the uncommitted data of the test transaction, so the test fails "mysteriously";@TransactionalEventListener(phase = AFTER_COMMIT)doesn't fire at all, because there's no commit;- deferred constraints and triggers are checked only at commit.
That's why in integration tests I often don't put @Transactional. I clean the data before each test: @Sql(scripts = "/clean.sql"), TRUNCATE ... CASCADE, or the repositories' deleteAll(). It's slower, but closer to the behavior in prod.
@Transactional tests have their place too: at the repository level they're fast and convenient. Just use them knowing what they don't check.
Sign up to mark studied questions and save your progress.