Golang / GoLang System Architecture and Testing Interview Questions
How do you structure integration tests in Go that require real databases or external services?
Integration tests verify that your code works with real infrastructure. Go's testing tools make this clean: build tags separate unit from integration tests, TestMain handles setup/teardown, and testcontainers-go spins up real dependencies in Docker.
// integration_test.go //go:build integration package repository_test import ( "context" "testing" "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/modules/postgres" ) var testDB *sql.DB // TestMain: shared setup/teardown for the whole package func TestMain(m *testing.M) { ctx := context.Background() // Start a real Postgres container pgContainer, err := postgres.RunContainer(ctx, testcontainers.WithImage("postgres:15"), postgres.WithDatabase("testdb"), postgres.WithUsername("test"), postgres.WithPassword("test"), ) if err != nil { log.Fatalf("container start: %v", err) } defer pgContainer.Terminate(ctx) dsn, _ := pgContainer.ConnectionString(ctx, "sslmode=disable") testDB, err = sql.Open("postgres", dsn) if err != nil { log.Fatalf("open db: %v", err) } // Run migrations if err := runMigrations(testDB); err != nil { log.Fatalf("migrate: %v", err) } os.Exit(m.Run()) // run all tests in the package } // Individual integration test using shared testDB func TestUserRepository_Save(t *testing.T) { repo := postgres.NewUserRepository(testDB) ctx := context.Background() t.Cleanup(func() { testDB.ExecContext(ctx, "DELETE FROM users WHERE email = $1", "test@example.com") }) user := &User{Name: "Test", Email: "test@example.com"} if err := repo.Save(ctx, user); err != nil { t.Fatalf("Save: %v", err) } if user.ID == 0 { t.Error("expected ID to be set after save") } got, err := repo.FindByID(ctx, user.ID) if err != nil { t.Fatalf("FindByID: %v", err) } if got.Email != user.Email { t.Errorf("got email %q, want %q", got.Email, user.Email) } } // Run integration tests: // go test -tags integration ./...
More Related questions...