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
// ...
})
}
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...
