Testing in Go
Go has a built-in testing framework in the standard library โ no third-party framework needed.
The go test Tool
Run tests with:
File naming rule: test files must end in _test.go. They are compiled and run by go test but excluded from normal builds.
Writing Tests with *testing.T
Test functions have the signature func TestXxx(t *testing.T) where Xxx starts with an uppercase letter:
Key *testing.T methods:
| Method | Behavior |
|---|---|
t.Error(args...) | Mark test failed, continue running |
t.Errorf(format, args...) | Mark test failed with formatted message, continue |
t.Fatal(args...) | Mark test failed, stop test immediately |
t.Fatalf(format, args...) | Mark test failed with formatted message, stop immediately |
t.Log(args...) | Log message (visible with -v flag) |
t.Logf(format, args...) | Log formatted message |
Use Fatal/Fatalf when subsequent assertions depend on a previous one succeeding.
Table-Driven Tests
The most idiomatic Go pattern: define test cases as a slice of structs, then loop:
This approach keeps test data and test logic separate, making it trivial to add new cases.
Subtests with t.Run
t.Run creates a named subtest, which shows up in output as TestAdd/positive. Each subtest can be run individually:
Run just one subtest: go test -run TestAdd/positive
Benchmarks with *testing.B
Benchmark functions have the signature func BenchmarkXxx(b *testing.B). The key is the b.N loop โ Go runs it enough times to get a stable measurement:
Run benchmarks with:
Output looks like:
-8 is the GOMAXPROCS value; 0.3 ns/op is time per iteration.
Example Tests
Example functions serve double duty โ they are both documentation and executable tests:
The // Output: comment is matched against actual stdout. If it doesn't match, the test fails. Examples appear in go doc output automatically.
Knowledge Check
What is the idiomatic Go pattern for testing multiple inputs and expected outputs in a single test function?
What is the difference between `t.Error` and `t.Fatal`?
Which flag runs all benchmarks in a Go package?