| H2 in-memory | Testcontainers | |
|---|---|---|
| Tốc độ | Cực nhanh (~ms) | Chậm (~5-10s startup) |
| Setup | Không cần Docker | Cần Docker daemon |
| Fidelity (giống prod) | Thấp — dialect khác Postgres/MySQL | Cao — DB thật |
| Stored procedure, extension | ❌ Không test được | ✅ |
| Migration script (Flyway) | Đôi khi fail (dialect) | ✅ Chạy đúng |
Vấn đề H2: SQL chạy OK trên H2 nhưng fail production vì dialect khác (NOW() vs CURRENT_TIMESTAMP, JSON column, regex syntax, full-text search). False sense of safety.
Hybrid strategy (recommended):
1. Unit test + H2 cho development loop nhanh (mỗi save chạy lại).
2. Testcontainers trong PR check + CI để catch integration bug.
3. Không shared test database (flaky, data pollution giữa các test).
Khi nào quan trọng dùng Testcontainers: critical path (payment, order processing), migration script test, stored procedure test, native query.
2026 trend: Testcontainers trở thành standard — Spring Boot 3.1+ @ServiceConnection giảm config friction đáng kể. CI cloud (GitHub Actions, GitLab CI) đã pre-installed Docker daemon.
| H2 in-memory | Testcontainers | |
|---|---|---|
| Speed | Extremely fast (~ms) | Slower (~5-10s startup) |
| Setup | No Docker needed | Requires a Docker daemon |
| Fidelity (prod-like) | Low — dialect differs from Postgres/MySQL | High — real DB |
| Stored procedures, extensions | ❌ Untestable | ✅ |
| Migration scripts (Flyway) | Sometimes fail (dialect) | ✅ Run correctly |
The H2 problem: SQL works on H2 but fails in production due to dialect differences (NOW() vs CURRENT_TIMESTAMP, JSON columns, regex syntax, full-text search). Gives a false sense of safety.
Hybrid strategy (recommended):
1. Unit tests + H2 for a fast dev loop (rerun on every save).
2. Testcontainers in PR checks + CI to catch integration bugs.
3. No shared test databases (flaky, cross-test data pollution).
When Testcontainers matters: critical paths (payments, order processing), migration script tests, stored procedure tests, native queries.
2026 trend: Testcontainers is becoming the standard — Spring Boot 3.1+ @ServiceConnection drastically reduces config friction. Cloud CI (GitHub Actions, GitLab CI) ships with Docker preinstalled.