Testcontainers spin up Docker container thật (Postgres, Redis, Kafka...) trong test — integration test với infra thật, không phải H2. Thêm dependency spring-boot-testcontainers + org.testcontainers:postgresql (scope test).
Spring Boot 3.1+ — @ServiceConnection:
java
@SpringBootTest
@Testcontainers
class UserRepositoryIT {
@Container
@ServiceConnection // tự config spring.datasource.* từ container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");
@Autowired UserRepository repo;
@Test void findByEmail() {
repo.save(new User("alice@ex.com"));
assertThat(repo.findByEmail("alice@ex.com")).isPresent();
}
}Lợi ích: test với Postgres thật → bắt lỗi SQL mà H2 bỏ qua; Flyway migration chạy đúng môi trường; CI không cần cài sẵn DB. Nhược: chậm hơn H2 (~5-10s startup) → share container để giảm. Chọn: H2 cho unit test service; Testcontainers cho integration test repository/DB.