Video in progress

Draw up a test strategy for the persistence layer for a team: H2, Testcontainers, slice tests and checking query counts.

The main test database is Testcontainers with the same database as prod. @DataJpaTest slice tests for mapping and queries, @SpringBootTest for a small number of full scenarios. The SQL count is asserted on important endpoints. H2 is only for very fast tests that don't depend on the database, or not at all.

📖 Answer

Green on H2, red on prod: a very familiar picture. Even in PostgreSQL mode, H2 handles jsonb, for update skip locked, partial indexes, some type conversions and lock behavior differently. So I give up on H2.

The layers:

@DataJpaTest + Testcontainers. Mapping, cascade, custom queries, projections. Fast, because only the JPA context starts. One container is reused for all tests (singleton or reuse).

@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
@Testcontainers
class OrderRepositoryTest {
    @Container @ServiceConnection
    static PostgreSQLContainer<?> pg = new PostgreSQLContainer<>("postgres:16-alpine");
}

One trap: @DataJpaTest runs each test in a transaction and rolls back at the end. If there is no flush, constraint errors never appear at all. That is why I call em.flush() and em.clear() before the assertion; otherwise you are testing the persistence context, not the database.

Concurrency tests. Optimistic/pessimistic locks, deadlocks: without a test transaction (@Transactional(propagation = NOT_SUPPORTED)), with two threads and a CountDownLatch.

Query count. For critical list endpoints, assertSelectCount(2) with datasource-proxy. N+1 regressions are caught here.

Migration. Apply all the Flyway scripts to a clean database and bring up the context with ddl-auto=validate: one test, but it prevents a lot of mistakes.

To keep CI time under control, it matters to reuse the container between tests and not to break the Spring context cache (don't put a different @MockBean in every test).