Testcontainers spin up real Docker containers (Postgres, Redis, Kafka...) trong test — test tích hợp với infrastructure thật, không phải H2 in-memory.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>Spring Boot 3.1+ — ServiceConnection:
@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_found() {
repo.save(new User("alice@ex.com"));
assertThat(repo.findByEmail("alice@ex.com")).isPresent();
}
}Lợi ích:
- Test với Postgres thật → phát hiện SQL syntax lỗi H2 bỏ qua.
- Flyway migration chạy đúng môi trường.
- Không cần pre-installed DB trên CI.
Nhược điểm: chậm hơn H2 (Docker startup ~5-10s). Fix: @TestcontainersConfiguration dùng shared containers.
Khi dùng H2: unit test service layer, không cần test SQL thật. Khi dùng Testcontainers: integration test repository/DB layer.
Testcontainers spins up real Docker containers (Postgres, Redis, Kafka…) during tests — integration testing with real infrastructure, not H2 in-memory.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>Spring Boot 3.1+ — ServiceConnection:
@SpringBootTest
@Testcontainers
class UserRepositoryIT {
@Container
@ServiceConnection // Auto-configures spring.datasource.* from the container
static PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>("postgres:16");
@Autowired UserRepository repo;
@Test
void findByEmail_found() {
repo.save(new User("alice@ex.com"));
assertThat(repo.findByEmail("alice@ex.com")).isPresent();
}
}Benefits:
- Tests with real Postgres → catches SQL syntax errors that H2 ignores.
- Flyway migrations run in the correct environment.
- No pre-installed DB required on CI.
Drawback: slower than H2 (Docker startup ~5-10s). Fix: use @TestcontainersConfiguration to share containers.
When to use H2: unit-testing the service layer, no need for real SQL. When to use Testcontainers: integration testing the repository/DB layer.