Testing and Benchmarking
Go's built-in testing package provides TestXxx functions, table-driven tests, BenchmarkXxx functions, and the testdata directory convention without external frameworks.
Go's testing package runs tests from files ending in _test.go. Functions named TestXxx use *testing.T; BenchmarkXxx functions measure repeated work with *testing.B.
Table-driven tests keep related inputs and expected results together. A benchmark loops for b.N iterations, which the test runner chooses.
package calc
import "testing"
func Add(a, b int) int { return a + b }
func TestAdd(t *testing.T) {
cases := []struct{ a, b, want int }{{2, 3, 5}, {0, 1, 1}}
for _, tc := range cases {
if got := Add(tc.a, tc.b); got != tc.want {
t.Errorf("Add() = %d, want %d", got, tc.want)
}
}
}
func BenchmarkAdd(b *testing.B) {
for b.Loop() {
Add(2, 3)
}
}In production
Run go test ./..., go test -race ./..., go vet ./..., and go test -coverprofile=coverage.out ./...; inspect coverage with go tool cover -func=coverage.out. Race builds run only on supported platforms and detect races only on code paths exercised by tests. Store package fixtures in testdata. Prefer b.Loop for new benchmarks because it keeps work in the loop body from being optimized away. Run benchmarks with go test -bench=.