Testing in Go – Writing Unit Tests and Benchmarks (Table-Driven)
Writing a Basic Test
Go's built-in testing package requires test files to end in _test.go and test functions to start with Test.
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("expected 5, got %d", result)
}
}
Table-Driven Tests
A common Go idiom for testing multiple input/output combinations concisely.
func TestAddTable(t *testing.T) {
cases := []struct {
a, b, expected int
}{
{1, 2, 3},
{5, 5, 10},
{-1, 1, 0},
}
for _, c := range cases {
result := Add(c.a, c.b)
if result != c.expected {
t.Errorf("Add(%d, %d) = %d; want %d", c.a, c.b, result, c.expected)
}
}
}
Writing Benchmarks
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
Add(2, 3)
}
}
Run tests with go test and benchmarks with go test -bench=.
PreviousFile Handling in Go – Read, Write, and Parse JSON/CSV Files
Next Working with Databases in Go – GORM and SQL Connections
Ready to master real-world Go skills?
Learn Go hands-on with mentor-led, live sessions.
.png)