Video in progress
What is Testcontainers, and why do you often pick it over H2 for integration tests?
Testcontainers starts Docker containers (PostgreSQL, Kafka, Redis and others) from inside the test and removes them when the test ends. You test against a real database of the same version as in prod, which eliminates false green results caused by dialect differences.
📖 Answer
H2 has a "PostgreSQL mode" too, but it's still an imitation. CREATE INDEX CONCURRENTLY in a Flyway migration, jsonb operators, SKIP LOCKED: none of these work correctly in H2.
The shortest setup in Spring Boot 3.1+:
@SpringBootTest
@Testcontainers
class PaymentIT {
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
@Test
void tolov_saqlanadi() { ... }
}
@ServiceConnection wires the container's URL, user and password into spring.datasource.* on its own. Before that you did this by hand with @DynamicPropertySource.
There's a cost too:
- you need Docker, on the CI agent and on every developer's machine;
- the image is downloaded on the first run, and after that the container starts in 2-5 seconds;
- if the field isn't
static, the container is recreated for every test method, which is very slow.
In practice, pin the image version to the one in prod (postgres:16), not latest. Otherwise the tests one day switch to a different version unexpectedly and give errors with no obvious cause.
Sign up to mark studied questions and save your progress.