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 ./...
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
