Testcontainers for Go: Real Databases in Your Go Tests

Testcontainers for Go: Real Databases in Your Go Tests

Go developers have long relied on mocks and in-memory fakes to test database interactions. These approaches work until they don't — and they often fail silently when your SQL queries, migrations, or Redis pipelines behave differently against a real engine than against a stub. Testcontainers for Go solves this by spinning up actual Docker containers as part of your test run.

What Is Testcontainers for Go?

Testcontainers for Go (github.com/testcontainers/testcontainers-go) is a Go library that programmatically manages Docker containers during tests. Each container starts before your test runs and is torn down automatically when the test finishes. No Docker Compose files to maintain, no shared state between CI runs.

Install it:

go get github.com/testcontainers/testcontainers-go

Setting Up a PostgreSQL Container

The most common use case is a real PostgreSQL database. Here is a complete example using the dedicated postgres module:

package db_test

import (
    "context"
    "database/sql"
    "testing"

    _ "github.com/lib/pq"
    "github.com/testcontainers/testcontainers-go"
    "github.com/testcontainers/testcontainers-go/modules/postgres"
    "github.com/testcontainers/testcontainers-go/wait"
)

func TestUserRepository(t *testing.T) {
    ctx := context.Background()

    pgContainer, err := postgres.RunContainer(ctx,
        testcontainers.WithImage("postgres:16-alpine"),
        postgres.WithDatabase("testdb"),
        postgres.WithUsername("testuser"),
        postgres.WithPassword("testpass"),
        testcontainers.WithWaitStrategy(
            wait.ForLog("database system is ready to accept connections").
                WithOccurrence(2),
        ),
    )
    if err != nil {
        t.Fatalf("failed to start postgres container: %v", err)
    }
    defer pgContainer.Terminate(ctx)

    connStr, err := pgContainer.ConnectionString(ctx, "sslmode=disable")
    if err != nil {
        t.Fatalf("failed to get connection string: %v", err)
    }

    db, err := sql.Open("postgres", connStr)
    if err != nil {
        t.Fatalf("failed to open db: %v", err)
    }
    defer db.Close()

    // Run your migrations
    _, err = db.ExecContext(ctx, `
        CREATE TABLE users (
            id   SERIAL PRIMARY KEY,
            name TEXT NOT NULL
        )
    `)
    if err != nil {
        t.Fatalf("migration failed: %v", err)
    }

    // Insert and query
    _, err = db.ExecContext(ctx, "INSERT INTO users (name) VALUES ($1)", "Alice")
    if err != nil {
        t.Fatalf("insert failed: %v", err)
    }

    var name string
    err = db.QueryRowContext(ctx, "SELECT name FROM users WHERE id = 1").Scan(&name)
    if err != nil {
        t.Fatalf("query failed: %v", err)
    }

    if name != "Alice" {
        t.Errorf("expected Alice, got %s", name)
    }
}

The wait.ForLog strategy ensures Go does not attempt a connection before PostgreSQL is ready. Without a wait strategy you will see flaky tests on slower machines.

Testing with Redis

The Redis module works the same way:

import (
    "github.com/testcontainers/testcontainers-go/modules/redis"
    goredis "github.com/redis/go-redis/v9"
)

func TestCacheLayer(t *testing.T) {
    ctx := context.Background()

    redisContainer, err := redis.RunContainer(ctx,
        testcontainers.WithImage("redis:7-alpine"),
    )
    if err != nil {
        t.Fatalf("failed to start redis: %v", err)
    }
    defer redisContainer.Terminate(ctx)

    endpoint, err := redisContainer.Endpoint(ctx, "")
    if err != nil {
        t.Fatalf("failed to get endpoint: %v", err)
    }

    client := goredis.NewClient(&goredis.Options{Addr: endpoint})
    defer client.Close()

    err = client.Set(ctx, "session:123", "user-data", 0).Err()
    if err != nil {
        t.Fatalf("SET failed: %v", err)
    }

    val, err := client.Get(ctx, "session:123").Result()
    if err != nil {
        t.Fatalf("GET failed: %v", err)
    }

    if val != "user-data" {
        t.Errorf("unexpected value: %s", val)
    }
}

Running Custom Containers

Not every dependency has a dedicated module. For anything else use GenericContainer:

func TestWithCustomImage(t *testing.T) {
    ctx := context.Background()

    req := testcontainers.ContainerRequest{
        Image:        "minio/minio:latest",
        ExposedPorts: []string{"9000/tcp"},
        Env: map[string]string{
            "MINIO_ROOT_USER":     "minioadmin",
            "MINIO_ROOT_PASSWORD": "minioadmin",
        },
        Cmd: []string{"server", "/data"},
        WaitingFor: wait.ForHTTP("/minio/health/live").WithPort("9000"),
    }

    container, err := testcontainers.GenericContainer(ctx,
        testcontainers.GenericContainerRequest{
            ContainerRequest: req,
            Started:          true,
        },
    )
    if err != nil {
        t.Fatalf("container start failed: %v", err)
    }
    defer container.Terminate(ctx)

    host, _ := container.Host(ctx)
    port, _ := container.MappedPort(ctx, "9000")

    endpoint := fmt.Sprintf("http://%s:%s", host, port.Port())
    // Use endpoint in your S3-compatible client
    _ = endpoint
}

Using TestMain for Shared Containers

Starting a fresh container for every test function is correct for isolation but slow when you have 50 tests hitting the same schema. Use TestMain to start one container per package:

var testDB *sql.DB

func TestMain(m *testing.M) {
    ctx := context.Background()

    pgContainer, err := postgres.RunContainer(ctx,
        testcontainers.WithImage("postgres:16-alpine"),
        postgres.WithDatabase("testdb"),
        postgres.WithUsername("testuser"),
        postgres.WithPassword("testpass"),
        testcontainers.WithWaitStrategy(
            wait.ForLog("database system is ready to accept connections").
                WithOccurrence(2),
        ),
    )
    if err != nil {
        log.Fatalf("postgres start failed: %v", err)
    }

    connStr, _ := pgContainer.ConnectionString(ctx, "sslmode=disable")
    testDB, _ = sql.Open("postgres", connStr)

    runMigrations(testDB)

    code := m.Run()

    pgContainer.Terminate(ctx)
    os.Exit(code)
}

Individual tests then use testDB and truncate tables between runs rather than recreating the container.

Wait Strategies

Testcontainers for Go ships several wait strategies:

Strategy Use when
wait.ForLog(...) Container prints a ready message to stdout
wait.ForListeningPort(...) A TCP port opens
wait.ForHTTP(...) An HTTP endpoint returns 2xx
wait.ForExec(...) A command exits with code 0

Combine them with wait.ForAll(...) when a container exposes multiple services.

Running in CI

Testcontainers needs Docker available. On GitHub Actions, Docker is pre-installed on ubuntu-latest. Add this to your workflow:

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: "1.22"
      - run: go test ./...

No extra setup required — the Docker daemon is already running.

Closing Thoughts

Testcontainers for Go removes the gap between your test environment and production. PostgreSQL quirks, Redis eviction policies, and S3-compatible storage edge cases surface in tests rather than on-call incidents.

Once your tests are green locally and in CI, pair them with HelpMeTest to run end-to-end monitoring around the clock. HelpMeTest can exercise your live service continuously so regressions are caught the moment they reach any environment — not just when a developer runs go test.

Read more

Start now free