02 / 04

How do you write integration tests for a Go service that depends on a PostgreSQL database?

Use testcontainers-go to spin up a real Postgres container per test suite, run migrations, and wrap each test in a transaction that is rolled back at the end for isolation.

Integration test with testcontainers
Integration test strategy
  1. 1

    Build tag //go:build integration keeps integration tests separate from unit tests

  2. 2

    Transaction rollback per test ensures test isolation without truncating tables

  3. 3

    TestMain sets up the container once per test suite — not per test case

  4. 4

    Pass tx (implementing DBTX interface) to the repository — works transparently

  5. 5

    Run in CI with: go test -tags=integration ./...