TExcelTAD
Home › Go › Go Testing

Go Testing

Go has testing built in. There is no framework to install: the testing package and the go test command are part of the standard toolchain. Tests live next to the code they test, in files ending in _test.go, and those files are only compiled when you run go test.

The rules

Rule Example
Test files end in _test.go mathx_test.go
Test functions start with Test + a capital letter func TestAdd(t *testing.T)
They take one parameter, t *testing.T
Failure is reported with t.Error, t.Errorf, t.Fatal, t.Fatalf t.Errorf("got %d, want %d", got, want)

t.Error/t.Errorf mark the test as failed but keep running; t.Fatal/t.Fatalf stop that test immediately.

A first test

Suppose package mathx has this function:

go
// mathx.go
package mathx

// Clamp limits v to the range [lo, hi].
func Clamp(v, lo, hi int) int {
	if v < lo {
		return lo
	}
	if v > hi {
		return hi
	}
	return v
}

The test goes into mathx_test.go in the same folder:

go
// mathx_test.go
package mathx

import "testing"

func TestClampInside(t *testing.T) {
	got := Clamp(5, 0, 10)
	if got != 5 {
		t.Errorf("Clamp(5, 0, 10) = %d; want 5", got)
	}
}

func TestClampBelow(t *testing.T) {
	if got := Clamp(-3, 0, 10); got != 0 {
		t.Errorf("Clamp(-3, 0, 10) = %d; want 0", got)
	}
}

Run all tests in the module:

bash
go test ./...
ok  	example.com/mathx	0.002s

Add -v (verbose) to see every test:

bash
go test -v ./...
=== RUN   TestClampInside
--- PASS: TestClampInside (0.00s)
=== RUN   TestClampBelow
--- PASS: TestClampBelow (0.00s)
PASS
ok  	example.com/mathx	0.002s

Table-driven tests

The most common Go testing style puts the cases in a table — a slice of anonymous structs — and loops over it. Adding a case is one line. t.Run creates a named subtest for each row.

go
func TestClamp(t *testing.T) {
	tests := []struct {
		name      string
		v, lo, hi int
		want      int
	}{
		{"inside", 5, 0, 10, 5},
		{"below", -3, 0, 10, 0},
		{"above", 42, 0, 10, 10},
		{"at upper edge", 10, 0, 10, 10},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := Clamp(tt.v, tt.lo, tt.hi); got != tt.want {
				t.Errorf("Clamp(%d, %d, %d) = %d; want %d", tt.v, tt.lo, tt.hi, got, tt.want)
			}
		})
	}
}

The playground cannot run go test, but it can run the same table logic inside main, so you can see how it works and break it on purpose. Change a want value and run it again:

go · try it yourself
package main

import "fmt"

func Clamp(v, lo, hi int) int {
	if v < lo {
		return lo
	}
	if v > hi {
		return hi
	}
	return v
}

func main() {
	tests := []struct {
		name      string
		v, lo, hi int
		want      int
	}{
		{"inside", 5, 0, 10, 5},
		{"below", -3, 0, 10, 0},
		{"above", 42, 0, 10, 10},
		{"at upper edge", 10, 0, 10, 10},
	}

	failed := 0
	for _, tt := range tests {
		got := Clamp(tt.v, tt.lo, tt.hi)
		if got != tt.want {
			failed++
			fmt.Printf("--- FAIL: TestClamp/%s: got %d, want %d\n", tt.name, got, tt.want)
			continue
		}
		fmt.Printf("--- PASS: TestClamp/%s\n", tt.name)
	}
	fmt.Printf("%d passed, %d failed\n", len(tests)-failed, failed)
}
--- PASS: TestClamp/inside
--- PASS: TestClamp/below
--- PASS: TestClamp/above
--- PASS: TestClamp/at upper edge
4 passed, 0 failed

What a failure looks like

If Clamp had an off-by-one bug — say it returned hi + 1 when v == hi — go test would print the file, line and your message, then FAIL:

bash
go test ./...
--- FAIL: TestClamp (0.00s)
    --- FAIL: TestClamp/at_upper_edge (0.00s)
        mathx_test.go:21: Clamp(10, 0, 10) = 11; want 10
FAIL
FAIL	example.com/mathx	0.003s
FAIL

Notice that spaces in subtest names become underscores. Run a single test (or subtest) with -run, which takes a regular expression: go test -run 'TestClamp/below' ./....

Helpers, benchmarks and examples

Function form Purpose Run with
func TestXxx(t *testing.T) correctness test go test
func BenchmarkXxx(b *testing.B) performance measurement go test -bench .
func ExampleXxx() with // Output: comment documentation that is also verified go test
func FuzzXxx(f *testing.F) fuzzing with generated inputs go test -fuzz FuzzXxx

An example function is a test whose expected output is a comment — and it appears in your package documentation:

go
func ExampleClamp() {
	fmt.Println(Clamp(15, 0, 10))
	// Output: 10
}

A benchmark loops with b.Loop() (Go 1.24+) and reports the time per operation:

go
func BenchmarkClamp(b *testing.B) {
	for b.Loop() {
		Clamp(42, 0, 10)
	}
}
bash
go test -bench . -benchmem
goos: linux
goarch: amd64
pkg: example.com/mathx
BenchmarkClamp-8   	1000000000	         0.2601 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	example.com/mathx	0.412s

Coverage and the race detector

bash
go test -cover ./...
go test -race ./...
ok  	example.com/mathx	0.002s	coverage: 100.0% of statements
ok  	example.com/mathx	1.015s

-cover reports how much of your code the tests execute; -race re-runs them with the data-race detector — essential for concurrent code.

Tip: Call t.Helper() at the start of your own assertion helpers. Failures are then reported at the line of the caller, not inside the helper.

Test yourself

Which file name makes Go treat a file as a test file?

  1. test_math.go
  2. math.test.go
  3. math_test.go
  4. math.spec.go

What is the difference between t.Errorf and t.Fatalf?

  1. None
  2. Errorf marks failure and continues; Fatalf marks failure and stops the test
  3. Fatalf crashes the whole program
  4. Errorf only logs

What is a table-driven test?

  1. A test that reads a CSV file
  2. A loop over a slice of test cases, often with t.Run subtests
  3. A database test
  4. A benchmark