testing package
The testing package is the standard library's test harness. A function func TestFoo(t *testing.T) in a _test.go file is a test. t.Error, t.Fatal, t.Run, and t.Cleanup are how you fail, stop, nest, and tear down.
Detailed Explanation
go test compiles packages with their _test.go files and runs every Test* with signature func TestXxx(*testing.T). You do not register tests. The name after Test must start with an uppercase letter (TestParse, not Testparse).
T is the test. t.Fatal fails and stops that function (via runtime.Goexit). t.Error fails and continues. t.Fatalf / t.Errorf format. t.Helper() marks a function so failure lines point at the caller. t.Cleanup(fn) runs fn after the test, LIFO, even on fatal — prefer it over defer when the test function launches helpers that need teardown after t.Run children.
External vs internal tests. package foo in a test file can see unexported names. package foo_test is another package and can only see exports — that is how you test the public API. Both can live in the same directory.
Examples and fuzz. Example functions become runnable docs. Fuzz is fuzzing. Benchmark is benchmarks. They share the testing package and _test.go files.
What it costs. Zero extra framework for most packages. Assertion libraries are optional; if got != want { t.Fatalf(...) } is the house style. Table-driven tests plus t.Run scale without a third-party runner.
Code Examples
package parse_test
import "testing"
func TestAtoi(t *testing.T) {
got, err := atoi("7")
if err != nil {
t.Fatal(err)
}
if got != 7 {
t.Fatalf("got %d", got)
}
}
func atoi(s string) (int, error) { return 7, nil }func TestHelper(t *testing.T) {
assertEq := func(got, want int) {
t.Helper()
if got != want {
t.Fatalf("%d != %d", got, want)
}
}
assertEq(1, 1)
}Common Gotchas
`Testfoo` is not a test
the name must be `Test` plus a capital letter (`TestFoo`). `testFoo` is an ordinary function.
`t.Fatal` in a different goroutine does not stop the test reliably
use `t.Error` plus a wait, or `t.Fail` from the main test goroutine after you receive the error.
`t.Parallel` plus shared mutable state races
isolate fixtures.
`_test.go` files are not in `go build` of the library
production binaries do not include them.