Testcontainersmedium3-5 years
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?
A static @Container field is one container per class, so the suite pays the container's start 20 times. Move to one container per JVM: declare the container once as a @ServiceConnection bean in a shared @TestConfiguration that every integration test imports (or a composed @IntegrationTest annotation), so Spring's context cache keeps the bean and the container runs until the JVM exits. Isolation then comes from each test cleaning up after itself (a rolled-back transaction, or TRUNCATE in @BeforeEach), not from a fresh database. withReuse(true) goes one step further and keeps the container alive between runs on a developer machine; it is a local convenience, not a CI setting.
PreviousA `@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.Next A CI job's Spring test phase went from 3 to 14 minutes over six months, while the number of tests grew by only 20%. CPU is high, the database is idle, and there are 60 `@SpringBootTest` and `@WebMvcTest` classes. What do you suspect, how do you measure it, and what changes would you make?