Video in progress

Strong Middle 🌱 Spring

What traps does putting @Transactional on a test lead to?

The test method runs inside a transaction that's rolled back at the end. The database stays clean, but it hides real commits, lazy loading, AFTER_COMMIT listeners and behavior on other threads — the test passes, and prod falls over.

📖 Answer

  1. LazyInitializationException gets hidden.
@SpringBootTest @Transactional
class OrderApiTest {
    @Test void returnsItems() {
        OrderDto dto = service.find(1L); // lazy items are used inside the service
        // the test transaction is open — the session is still alive, so no error
    }
}

In prod the session closes when you leave the service, and that's exactly where the error shows up.

  1. @TransactionalEventListener(AFTER_COMMIT) doesn't fire at all — there's no commit.

  2. Other threads don't see the data. A controller called over HTTP with RANDOM_PORT runs on its own thread and in its own transaction, so rows the test wrote but didn't commit are invisible to it.

  3. Since there's no flush, constraint violations aren't caught either.

What you can do: write the test without a transaction and clean the tables before each test (@Sql("/clean.sql"), TRUNCATE ... CASCADE), or have each test create its own unique data. It's a bit slower, but the real flow gets tested.

In narrow repository tests like @DataJpaTest the transaction is convenient — just don't forget flush()/clear().