Programming Languages
Go
Subjective
Oct 04, 2025
Explain Go testing patterns and best practices.
Detailed Explanation
Go Testing Patterns:
• Table-driven tests
• Subtests with t.Run()
• Test helpers with t.Helper()
• Benchmarks with testing.B
• Examples with testable output
• Test coverage analysis
Table-driven test:
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
want int
}{
{"positive", 2, 3, 5},
{"negative", -1, -2, -3},
{"zero", 0, 5, 5},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Add(tt.a, tt.b); got != tt.want {
t.Errorf("Add(%d, %d) = %d, want %d", tt.a, tt.b, got, tt.want)
}
})
}
}
Benchmark:
func BenchmarkFib(b *testing.B) {
for i := 0; i < b.N; i++ {
Fib(20)
}
}
Mocking:
• Interfaces for dependency injection
• testify/mock for complex mocking
• httptest for HTTP testing
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts