Go by Example

Testing and Benchmarking

Write tests that check results and benchmarks that measure how long code takes.

Go's testing package runs functions in files ending in _test.go. A test function whose name starts with Test checks that code returns the expected result. A benchmark function whose name starts with Benchmark repeats work to measure how long it takes.

This table-driven test keeps several inputs and expected results together. If any result differs, t.Errorf marks the test as failed. The benchmark uses b.Loop to repeat the operation while Go measures how long it takes.

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 ./... to run tests in all packages. Use go test -race ./... to check for unsafe shared access while tests run; it can only find problems that the tests exercise. Run go test -bench=. to measure benchmark functions. Keep test input files in a folder named testdata.

Enjoyed this? Get more software craft delivered to your inbox.