| name | golang-testing |
| description | Go testing patterns including table-driven tests, subtests, benchmarks, fuzzing, and test coverage. Follows TDD methodology with idiomatic Go practices. |
Go Testing Patterns
Comprehensive Go testing patterns for writing reliable, maintainable tests following TDD methodology.
When to Activate
- Writing new Go functions or methods
- Adding test coverage to existing code
- Creating benchmarks for performance-critical code
- Implementing fuzz tests for input validation
- Following TDD workflow in Go projects
TDD Workflow for Go
The RED-GREEN-REFACTOR Cycle
RED → Write a failing test first
GREEN → Write minimal code to pass the test
REFACTOR → Improve code while keeping tests green
REPEAT → Continue with next requirement
For detailed step-by-step examples, see references/code-examples.md.
Table-Driven Tests
The standard pattern for Go tests. Enables comprehensive coverage with minimal code.
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"positive numbers", 2, 3, 5},
{"negative numbers", -1, -2, -3},
{"zero values", 0, 0, 0},
{"mixed signs", -1, 1, 0},
{"large numbers", 1000000, 2000000, 3000000},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := Add(tt.a, tt.b)
if got != tt.expected {
t.Errorf("Add(%d, %d) = %d; want %d",
tt.a, tt.b, got, tt.expected)
}
})
}
}
See references/code-examples.md for error handling patterns and advanced error case testing.
Subtests and Sub-benchmarks
Organizing Related Tests
func TestUser(t *testing.T) {
db := setupTestDB(t)
t.Run("Create", func(t *testing.T) {
user := &User{Name: "Alice"}
err := db.CreateUser(user)
if err != nil {
t.Fatalf("CreateUser failed: %v", err)
}
if user.ID == "" {
t.Error("expected user ID to be set")
}
})
t.Run("Get", func(t *testing.T) {
user, err := db.GetUser("alice-id")
if err != nil {
t.Fatalf("GetUser failed: %v", err)
}
if user.Name != "Alice" {
t.Errorf("got name %q; want %q", user.Name, "Alice")
}
})
t.Run("Update", func(t *testing.T) {
})
t.Run("Delete", func(t *testing.T) {
})
}
Parallel Subtests
func TestParallel(t *testing.T) {
tests := []struct {
name string
input string
}{
{"case1", "input1"},
{"case2", "input2"},
{"case3", "input3"},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
result := Process(tt.input)
_ = result
})
}
}
Test Helpers
Helper Functions
func setupTestDB(t *testing.T) *sql.DB {
t.Helper()
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("failed to open database: %v", err)
}
t.Cleanup(func() {
db.Close()
})
if _, err := db.Exec(schema); err != nil {
t.Fatalf("failed to create schema: %v", err)
}
return db
}
func assertNoError(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func assertEqual[T comparable](t *testing.T, got, want T) {
t.Helper()
if got != want {
t.Errorf("got %v; want %v", got, want)
}
}
Temporary Files and Directories
func TestFileProcessing(t *testing.T) {
tmpDir := t.TempDir()
testFile := filepath.Join(tmpDir, "test.txt")
err := os.WriteFile(testFile, []byte("test content"), 0644)
if err != nil {
t.Fatalf("failed to create test file: %v", err)
}
result, err := ProcessFile(testFile)
if err != nil {
t.Fatalf("ProcessFile failed: %v", err)
}
_ = result
}
Golden Files Pattern
Golden files are reference outputs stored in testdata/ for testing against known-good results. Use go test -args -update to refresh them when behavior changes intentionally. See references/code-examples.md for full implementation.
Mocking with Interfaces
Use interfaces for dependency injection and create mock implementations for tests:
- Define dependencies as interfaces
- Create production implementations
- Create mock implementations with function fields for tests
- Inject mocks into code under test
See references/code-examples.md for complete mock examples.
Benchmarks
Basic Benchmarks
func BenchmarkProcess(b *testing.B) {
data := generateTestData(1000)
b.ResetTimer()
for i := 0; i < b.N; i++ {
Process(data)
}
}
Use b.Run() for sub-benchmarks with different sizes or configurations. See references/code-examples.md for examples comparing multiple approaches.
Memory Allocation Optimization
Compare allocation strategies with -benchmem flag. See references/code-examples.md for detailed memory allocation comparison examples.
Fuzzing (Go 1.18+)
Basic Fuzz Test
func FuzzParseJSON(f *testing.F) {
f.Add(`{"name": "test"}`)
f.Add(`{"count": 123}`)
f.Add(`[]`)
f.Add(`""`)
f.Fuzz(func(t *testing.T, input string) {
var result map[string]interface{}
err := json.Unmarshal([]byte(input), &result)
if err != nil {
return
}
_, err = json.Marshal(result)
if err != nil {
t.Errorf("Marshal failed after successful Unmarshal: %v", err)
}
})
}
Add seed corpus with f.Add() and verify properties that must always hold true. For multiple input parameters and property validation, see references/code-examples.md.
Test Coverage
Running Coverage
go test -cover ./...
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out
go tool cover -func=coverage.out
go test -race -coverprofile=coverage.out ./...
Coverage Targets
| Code Type | Target |
|---|
| Critical business logic | 100% |
| Public APIs | 90%+ |
| General code | 80%+ |
| Generated code | Exclude |
Excluding Generated Code from Coverage
HTTP Handler Testing
Use httptest.NewRequest() and httptest.NewRecorder() for testing handlers without starting a server. Combine with table-driven tests for comprehensive coverage of different HTTP methods, paths, and response codes. See references/code-examples.md for full examples.
Testing Commands
go test ./...
go test -v ./...
go test -run TestAdd ./...
go test -run "TestUser/Create" ./...
go test -race ./...
go test -cover -coverprofile=coverage.out ./...
go test -short ./...
go test -timeout 30s ./...
go test -bench=. -benchmem ./...
go test -fuzz=FuzzParse -fuzztime=30s ./...
go test -count=10 ./...
Best Practices
Effective Patterns:
- Write tests first (TDD)
- Use table-driven tests for comprehensive coverage
- Test behavior, not implementation
- Use
t.Helper() in helper functions
- Use
t.Parallel() for independent tests
- Clean up resources with
t.Cleanup()
- Use meaningful test names that describe the scenario
- Test error paths thoroughly
- Prefer integration tests over mocking when possible
Avoid:
- Testing private functions directly (test through public API)
- Using
time.Sleep() in tests (use channels or conditions)
- Leaving flaky tests unfixed or unremoved
- Over-mocking instead of testing real behavior
Integration with CI/CD
See references/code-examples.md for a GitHub Actions CI/CD example with coverage validation.