Spring Boot test slicesmedium3-5 years

A `@DataJpaTest` persists three orders with `TestEntityManager` and asserts on `findById` and a derived query. It is green, but in production the same repository fails: a native query uses `DISTINCT ON`, and an `@Convert`-mapped column reads back wrong. Also, an `@TransactionalEventListener(phase = AFTER_COMMIT)` handler is never invoked in any repository test. Explain all three with what the slice does by default.

Three defaults are at work. @DataJpaTest replaces your datasource with an embedded H2 unless told otherwise, so SQL that PostgreSQL accepts and H2 does not (or the reverse) is tested against the wrong database; @AutoConfigureTestDatabase(replace = NONE) plus a real PostgreSQL in a container fixes that. Every test runs inside a transaction that is rolled back, so nothing ever commits and an after-commit listener never fires. And the persisted entities are still in the persistence context, so findById hands back the object you just created without reading the row, and a mapping or converter bug never shows: em.flush(); em.clear(); before the reads forces the data through the database and back.

The lesson behind it →
More on Spring Boot test slices