Testcontainers khởi động Docker container thật (Postgres, Kafka, Redis, MongoDB) trong test → test trên infrastructure thật, không phải H2 in-memory hay mock.
@SpringBootTest
@Testcontainers
class UserRepositoryTest {
@Container
static PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>("postgres:16-alpine");
// Spring Boot 3.1+: tự override datasource
@ServiceConnection static PostgreSQLContainer<?> db = postgres;
@Autowired UserRepository repo;
@Test
void findByEmail_real_schema() {
repo.save(new User("ada@example.com"));
assertThat(repo.findByEmail("ada@example.com")).isPresent();
}
}Lợi ích: test trên schema thật, SQL syntax thật, migration thật → bắt bug mà H2/mock miss (index, FK constraint, trigger, dialect khác).
Trade-off: chậm hơn unit test (~5-10s khởi động container), nhưng nhanh hơn deploy lên test server. Reuse container qua @Container static — khởi động 1 lần cho cả test class.
Spring Boot 3.1+ @ServiceConnection: tự override datasource URL/credential → không cần @DynamicPropertySource thủ công.
Best practice: DAO test, Kafka producer/consumer test, Redis cache test. Đừng dùng cho unit test (slow).
Testcontainers spins up real Docker containers (Postgres, Kafka, Redis, MongoDB) during tests → tests run against real infrastructure, not H2 in-memory or mocks.
@SpringBootTest
@Testcontainers
class UserRepositoryTest {
@Container
static PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>("postgres:16-alpine");
// Spring Boot 3.1+: auto-overrides the datasource
@ServiceConnection static PostgreSQLContainer<?> db = postgres;
@Autowired UserRepository repo;
@Test
void findByEmail_real_schema() {
repo.save(new User("ada@example.com"));
assertThat(repo.findByEmail("ada@example.com")).isPresent();
}
}Benefits: tests run on the real schema, real SQL syntax, real migrations → catches bugs that H2/mocks miss (indexes, FK constraints, triggers, dialect differences).
Trade-off: slower than unit tests (~5-10s container startup), but much faster than deploying to a test server. Reuse containers with @Container static — starts once for the whole test class.
Spring Boot 3.1+ @ServiceConnection: auto-overrides datasource URL/credentials → no manual @DynamicPropertySource.
Best practice: DAO tests, Kafka producer/consumer tests, Redis cache tests. Avoid in unit tests (slow).