Skip to content

Lesson 5 of 9 · 27m

Integration Tests, Testcontainers, and Migrations

Prove migrations, repository behavior, and messaging against realistic dependencies while keeping integration tests deterministic and reviewable.

The worst integration test suites are expensive simulations of hope. They boot half the world, share mutable state, depend on test order, and fail only after the pull request author has emotionally moved on. Good integration tests are narrower and more boring: run the real migration, connect to a realistic database, exercise one boundary, and leave no mystery state behind.

Test what the deployment will actually run

If production runs PostgreSQL 16, integration tests should not celebrate success on H2's compatibility mode:

@Testcontainers
@SpringBootTest
class MigrationIntegrationTest {
    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres =
        new PostgreSQLContainer<>("postgres:16-alpine")
            .withDatabaseName("app_test")
            .withUsername("app")
            .withPassword("test-password");

    @Test
    void applicationStartsAfterMigrations() {
        // Context startup is the assertion: migration failure fails the test.
    }
}

Flyway or Liquibase must run in the same order and with the same migration set the deployment uses. A test database created by Hibernate ddl-auto=update can hide exactly the migration defect you need to catch.

Migrations deserve production discipline

Never edit a migration that has already run in a shared environment. Add a new one. Keep migrations small, backward compatible during rolling deployment, and explicit about indexes or backfills:

ALTER TABLE orders ADD COLUMN idempotency_key varchar(80);
CREATE UNIQUE INDEX CONCURRENTLY orders_idempotency_key_uq
    ON orders(idempotency_key) WHERE idempotency_key IS NOT NULL;

Be careful: CREATE INDEX CONCURRENTLY cannot run inside a transaction in PostgreSQL, so migration tooling configuration matters. Large backfills often need separate batch jobs rather than a deploy-time migration that locks a table for minutes.

Isolate state and make cleanup boring

Tests fail together when they share rows, queues, cache keys, or files. Use unique tenant IDs, unique email addresses, or generated object IDs per test:

UUID tenantId = UUID.randomUUID();
String email = "user-" + tenantId + "@example.test";

Transactions can rollback database state for some tests, but rollback does not undo messages already consumed by another thread or side effects in external systems. Know which resources transactional cleanup cannot protect.

Field notes

  • Reusing containers speeds suites, but understand the lifecycle; shared mutable containers can hide state leaks.
  • Migration tests should include destructive or constraint-change cases, not only additive happy paths.
  • ddl-auto=validate is useful when mappings should match managed migrations; update is not production schema management.
  • Testcontainers startup failures often mean Docker socket or network issues, not application failure; surface that distinction clearly.
  • Keep at least one test that starts the exact production configuration shape with secrets replaced by test values.

Was this lesson helpful?

Sign in to rate