testing

Guided tour · Testing · pkg.go.dev →

Unit tests, benchmarks, fuzz tests, examples. Run with `go test`. File suffix _test.go.

Unit tests

func TestXxx(t *testing.T)

func TestAdd(t *testing.T) {
    got := Add(2, 3)
    if got != 5 {
        t.Errorf("Add(2,3) = %d, want 5", got)
    }
}

Table-driven

func TestAbs(t *testing.T) {
    tests := []struct{
        name string
        in, want int
    }{
        {"positive", 3, 3},
        {"negative", -3, 3},
        {"zero", 0, 0},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := Abs(tt.in); got != tt.want {
                t.Errorf("Abs(%d) = %d, want %d", tt.in, got, tt.want)
            }
        })
    }
}

Fail vs Skip vs Fatal

t.Error("continue running after logging")
t.Fatal("abort this test now")
t.Skip("skipping on this platform")
t.Helper() // mark helper — errors report caller line

Cleanup / TempDir

dir := t.TempDir() // auto-removed
t.Cleanup(func() { close(ch) })

Parallel

func TestThing(t *testing.T) {
    t.Parallel()
    // ...
}

Benchmarks

func BenchmarkXxx(b *testing.B)

func BenchmarkEncode(b *testing.B) {
    data := make([]byte, 1024)
    b.ResetTimer()
    for b.Loop() { // Go 1.24+; or: for i := 0; i < b.N; i++
        _ = encode(data)
    }
}

Report allocations

b.ReportAllocs()
b.ReportMetric(float64(ops)/b.Elapsed().Seconds(), "ops/s")

Fuzz tests

func FuzzXxx(f *testing.F)

func FuzzReverse(f *testing.F) {
    f.Add("hello")
    f.Fuzz(func(t *testing.T, s string) {
        r := Reverse(Reverse(s))
        if r != s {
            t.Errorf("double reverse changed %q -> %q", s, r)
        }
    })
}

Examples (runnable docs)

func ExampleXxx

func ExampleHello() {
    fmt.Println(Hello("world"))
    // Output: hello, world
}

Running tests

CLI

go test ./...                  # all packages
go test -run TestAdd -v        # one test
go test -bench=. -benchmem     # benchmarks
go test -fuzz=FuzzReverse      # fuzz
go test -race                  # race detector
go test -cover -coverprofile=c.out