Go Testing Basics
Write tests with the testing package and run them with go test, including running a single test and verbose output.
Testing is built into Go. This section covers writing a test and the go test flags you will use every day.
Writing Your First Test
func TestSlug(t *testing.T) {
if got := Slug("Hello World"); got != "hello-world" {
t.Errorf("got %q, want %q", got, "hello-world")
}
}
Tests live in _test.go files next to the code. t.Errorf keeps going, t.Fatalf stops.
Running Tests with go test
go test ./..., -run for one test, -v for output, -count=1 to skip the cache, -race for concurrency.
No per-file test runs:
Go tests run per package. Use -run with a name pattern instead of passing file names.
Summary
Name tests TestXxx, put them next to the code, and run go test ./... often.
Writing Your First Test in Go
How Go tests work with the built-in testing package, _test.go files, Test functions, t.Errorf vs t.Fatalf, and reading a failing test.
Running Tests with go test
Run all tests in a Go project, run one test or one file, show verbose output, disable caching with -count=1, add timeouts, and run tests in parallel.