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.
PreviousAfter a refactor, twelve tests fail with `UnnecessaryStubbingException` even though no assertion changed. A teammate proposes `@MockitoSettings(strictness = Strictness.LENIENT)` on the base class. What is Mockito telling you, why is lenient the wrong default, and what do these failures usually reveal about the tests?Next A Spring Boot service has 20 integration test classes, each with `@Testcontainers` and its own `@Container static PostgreSQLContainer`. The suite takes 6 minutes and most of it is containers starting. How would you restructure it, how do tests stay isolated afterwards, and where does `withReuse(true)` fit?