How to Use Testcontainers for Integration Tests in Go

Use the testcontainers-go library to start real Docker containers for integration testing by defining a container request and running it with the GenericContainer function.

Testcontainers for Go requires installing the testcontainers-go library and configuring Docker access before starting containers in your test setup. Add the dependency to your module, import the package, and use genericContainer.Run to spin up services like databases or message queues within your TestMain or individual test functions.

import (
	"github.com/testcontainers/testcontainers-go"
	"github.com/testcontainers/testcontainers-go/wait"
)

func TestIntegration(t *testing.T) {
	ctx := context.Background()
	req := testcontainers.ContainerRequest{
		Image:        "postgres:15",
		ExposedPorts: []string{"5432/tcp"},
		WaitingFor:   wait.ForLog("database system is ready to accept connections"),
	}
	container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
		ContainerRequest: req,
		Started:          true,
	})
	if err != nil {
		t.Fatal(err)
	}
	defer container.Terminate(ctx)
	// Use container to get host port and run DB tests
}