CodeNebula
Go📦Standard Libraryintermediate

testing — Unit Tests and Benchmarks

Go · Standard Library · Run with go run

Explanation

Go's built-in testing package requires no third-party dependencies. Test files end in `_test.go`, test functions start with `Test`, benchmark functions with `Benchmark`. `t.Fatal` / `t.Error` report failures. Table-driven tests (`t.Run`) group related cases. `go test ./...` runs all tests; `-bench=.` runs benchmarks; `-race` enables the race detector.

Real-World Scenario

Testing a JSON parser with table-driven tests: define a slice of `{input, expected, wantErr}` cases, loop over them with `t.Run(name, func(t *testing.T){...})`, and get one test name per case in the output — easy to identify which input failed.

Quick Snippet

snippet.go
func TestAdd(t *testing.T) {
    cases := []struct{
        a, b, want int
    }{
        {1, 2, 3},
        {0, 0, 0},
        {-1, 1, 0},
    }
    for _, tc := range cases {
        t.Run(fmt.Sprintf("%d+%d", tc.a, tc.b), func(t *testing.T) {
            got := Add(tc.a, tc.b)
            if got != tc.want {
                t.Errorf("got %d, want %d", got, tc.want)
            }
        })
    }
}

func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Add(i, i+1)
    }
}

Full Example

testing_basics.go
// Compile: go test -run TestAdd
// Note: testing functions live in *_test.go files. This file shows the
// shape of a table-driven test and a benchmark for reference.
// Output (from `go test`):
//   PASS
//   ok      example/add    0.001s
package main

import (
	"fmt"
	"testing"
)

func Add(a, b int) int { return a + b }

func TestAdd(t *testing.T) {
	cases := []struct {
		a, b, want int
	}{
		{1, 2, 3},
		{0, 0, 0},
		{-1, 1, 0},
	}
	for _, tc := range cases {
		t.Run(fmt.Sprintf("%d+%d", tc.a, tc.b), func(t *testing.T) {
			if got := Add(tc.a, tc.b); got != tc.want {
				t.Errorf("Add(%d,%d) = %d, want %d", tc.a, tc.b, got, tc.want)
			}
		})
	}
}

func BenchmarkAdd(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Add(i, i+1)
	}
}

func main() {
	fmt.Println("run with: go test -run TestAdd")
}
Run command
go run main.go