Golang / GoLang Production Patterns and Web Standards Interview Questions
What are table-driven tests in Go and why are they the preferred testing pattern?
Table-driven tests define multiple test cases as a slice of structs, then iterate over them running each case. This is Go's idiomatic testing pattern — it reduces duplication, makes it easy to add new cases, and provides clear failure messages identifying which case failed.
func divide(a, b float64) (float64, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } func TestDivide(t *testing.T) { tests := []struct { name string a, b float64 want float64 wantErr bool }{ {name: "positive division", a: 10, b: 2, want: 5, wantErr: false}, {name: "negative result", a: -6, b: 3, want: -2, wantErr: false}, {name: "division by zero", a: 5, b: 0, want: 0, wantErr: true}, {name: "float division", a: 7, b: 2, want: 3.5, wantErr: false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := divide(tt.a, tt.b) if (err != nil) != tt.wantErr { t.Errorf("divide(%v, %v) error = %v, wantErr = %v", tt.a, tt.b, err, tt.wantErr) return } if !tt.wantErr && got != tt.want { t.Errorf("divide(%v, %v) = %v, want %v", tt.a, tt.b, got, tt.want) } }) } } // Run specific subtests: go test -run TestDivide/division_by_zero // Parallel subtests: for _, tt := range tests { tt := tt // capture range var (pre-Go 1.22) t.Run(tt.name, func(t *testing.T) { t.Parallel() // run subtests in parallel // ... }) }
More Related questions...