Lesson 19 of 20 · Part 6: Real-world Go
Testing and benchmarks
Testing in Go for beginners. Write unit tests with go test, table-driven tests and subtests, example functions, test coverage and benchmarks, with real output.
5 min read · Updated · Beginner friendly
What you'll learn
- Write and run unit tests with the testing package and go test
- Use table-driven tests and subtests
- Document code with example functions that are also tests
- Measure coverage and write a benchmark
How do you know your code works? You could run it and check the output by eye, but that doesn’t scale, and it won’t catch the bug you introduce next month. Automated tests check your code for you, in seconds, every time you change something. Go has testing built in: no framework to install, just the testing package and the go test command.
The code we’ll test
We’ll test a small package called textutil, in a module called example.com/textutil:
// Package textutil has small helpers for working with text.
package textutil
import "strings"
// Reverse returns s with its characters in reverse order.
func Reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
// IsPalindrome reports whether s reads the same backwards,
// ignoring case and spaces.
func IsPalindrome(s string) bool {
clean := strings.ToLower(strings.ReplaceAll(s, " ", ""))
return clean == Reverse(clean)
}
// WordCount returns the number of words in s.
func WordCount(s string) int {
return len(strings.Fields(s))
}Your first test
Tests live in files whose names end in _test.go, next to the code they test. A test is a function whose name starts with Test and that takes a *testing.T:
package textutil
import "testing"
func TestReverse(t *testing.T) {
got := Reverse("gopher")
want := "rehpog"
if got != want {
t.Errorf("Reverse(%q) = %q, want %q", "gopher", got, want)
}
}Run all tests in the current package:
go testPASS
ok example.com/textutil 0.207sThe pattern is always the same: call the code, compare what you got with what you want, and report a mismatch with t.Errorf. Go deliberately has no special assertion library: a test is just ordinary Go code with if.
t.Errorfreports a failure and continues the test.t.Fatalfreports a failure and stops this test immediately. Use it when continuing makes no sense, such as after an unexpected error._test.gofiles are only compiled bygo test, never into your program.
Table-driven tests
To test many inputs, don’t copy and paste test functions. Put the cases in a table (a slice of anonymous structs, as you saw in lesson 8) and loop over it. Each case runs as a named subtest with t.Run:
func TestIsPalindrome(t *testing.T) {
tests := []struct {
name string
input string
want bool
}{
{"single word", "level", true},
{"mixed case", "Racecar", true},
{"with spaces", "never odd or even", true},
{"not a palindrome", "gopher", false},
{"empty string", "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := IsPalindrome(tt.input); got != tt.want {
t.Errorf("IsPalindrome(%q) = %v, want %v", tt.input, got, tt.want)
}
})
}
}Adding a new case is now one line. This is the standard way to write tests in Go, and you’ll see it in nearly every Go project.
Run with -v (verbose) to see every test and subtest:
go test -v=== RUN TestReverse
--- PASS: TestReverse (0.00s)
=== RUN TestIsPalindrome
=== RUN TestIsPalindrome/single_word
=== RUN TestIsPalindrome/mixed_case
=== RUN TestIsPalindrome/with_spaces
=== RUN TestIsPalindrome/not_a_palindrome
=== RUN TestIsPalindrome/empty_string
--- PASS: TestIsPalindrome (0.00s)
--- PASS: TestIsPalindrome/single_word (0.00s)
--- PASS: TestIsPalindrome/mixed_case (0.00s)
--- PASS: TestIsPalindrome/with_spaces (0.00s)
--- PASS: TestIsPalindrome/not_a_palindrome (0.00s)
--- PASS: TestIsPalindrome/empty_string (0.00s)
PASS
ok example.com/textutil 0.207sWhat a failure looks like
Suppose someone “simplifies” IsPalindrome and accidentally removes strings.ToLower. Running the tests catches it straight away:
--- FAIL: TestIsPalindrome (0.00s)
--- FAIL: TestIsPalindrome/mixed_case (0.00s)
textutil_test.go:29: IsPalindrome("Racecar") = false, want true
FAIL
exit status 1
FAIL example.com/textutil 0.424sThe output tells you which subtest failed, the file and line, and your own message with the input, the result and the expected value. That’s why a good error message includes all three.
To run just some tests, pass a regular expression to -run. Subtest names use /, and spaces become underscores:
go test -run TestIsPalindrome/mixed -v=== RUN TestIsPalindrome
=== RUN TestIsPalindrome/mixed_case
--- PASS: TestIsPalindrome (0.00s)
--- PASS: TestIsPalindrome/mixed_case (0.00s)
PASS
ok example.com/textutil 0.198sExample functions: documentation that is tested
An example function starts with Example, prints something, and ends with an // Output: comment. go test runs it and checks the output matches. And go doc and pkg.go.dev show it as documentation. Examples often go in a separate _test package, so they use the package exactly as a user would:
package textutil_test
import (
"fmt"
"example.com/textutil"
)
func ExampleReverse() {
fmt.Println(textutil.Reverse("Hello, 世界"))
// Output: 界世 ,olleH
}
func ExampleWordCount() {
fmt.Println(textutil.WordCount(" Go is fun "))
// Output: 3
}If the real output ever differs from the comment, the example fails like any other test, so your documentation can never go out of date.
Test coverage
Coverage tells you which lines of your code the tests actually ran:
go test -coverPASS
coverage: 100.0% of statements
ok example.com/textutil 0.425sTo see exactly which lines are covered, write a profile and open it as a coloured HTML page:
go test -coverprofile=cover.out
go tool cover -html=cover.outHigh coverage is useful, but it isn’t the goal on its own. A line can be covered by a test that checks nothing. Focus on testing behaviour that matters and edge cases (empty input, zero, very large values, unusual characters).
Benchmarks
A benchmark measures how fast code runs. Its name starts with Benchmark and it takes a *testing.B. The code to measure goes inside a for b.Loop() loop (Go 1.24+), and Go runs it as many times as needed for a reliable measurement:
func BenchmarkReverse(b *testing.B) {
for b.Loop() {
Reverse("the quick brown fox jumps over the lazy dog")
}
}Benchmarks only run when you ask for them with -bench. Adding -run '^$' skips the normal tests:
go test -bench . -run '^$'goos: windows
goarch: amd64
pkg: example.com/textutil
cpu: AMD Ryzen 7 7735HS with Radeon Graphics
BenchmarkReverse-16 4268212 281.7 ns/op
PASS
ok example.com/textutil 1.413sReverse ran about 4.3 million times, taking about 282 nanoseconds each time. Your numbers will differ with your computer. Benchmarks are most useful for comparing: measure, change the code, measure again. Add -benchmem to also see memory allocations.
Testing tips
- Test behaviour, not implementation. Test what a function returns, not how it does it, so you can refactor freely.
- Keep tests fast. Fast tests get run often. Avoid real networks and sleeps; use
httptest(lesson 18) and in-memory readers likestrings.NewReader. - Run
go test ./...to test every package in your module, and add-raceto catch data races (lesson 17). - Use helpers. Mark a helper function with
t.Helper()so failures point at the calling line. - Write a failing test first when you fix a bug. It proves the bug exists, then proves it’s fixed, and stops it coming back.
Go also supports fuzzing (func FuzzXxx(f *testing.F)), which generates random inputs to find edge cases you didn’t think of. It’s a great next step once you’re comfortable with regular tests.
Exercises
1. Test WordCount. Write a table-driven TestWordCount with at least four cases: an empty string, one word, several words, and extra spaces and tabs.
Show solution
func TestWordCount(t *testing.T) {
tests := []struct {
name string
input string
want int
}{
{"empty", "", 0},
{"one word", "gopher", 1},
{"sentence", "Go is fun", 3},
{"extra whitespace", " Go \t is\n fun ", 3},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := WordCount(tt.input); got != tt.want {
t.Errorf("WordCount(%q) = %d, want %d", tt.input, got, tt.want)
}
})
}
}2. Test an error case. Recall parsePercent from lesson 11. Write a test that checks it returns an error for "150" and for "abc", and no error for "42".
Show solution
func TestParsePercent(t *testing.T) {
tests := []struct {
input string
want int
wantErr bool
}{
{"42", 42, false},
{"150", 0, true},
{"abc", 0, true},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
got, err := parsePercent(tt.input)
if (err != nil) != tt.wantErr {
t.Fatalf("parsePercent(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
}
if got != tt.want {
t.Errorf("parsePercent(%q) = %d, want %d", tt.input, got, tt.want)
}
})
}
}The wantErr bool field is a common way to include error cases in a table.
Recap
- Tests live in
_test.gofiles; test functions arefunc TestXxx(t *testing.T). go testruns them;-vshows details,-runfilters,-coverreports coverage.- Table-driven tests with
t.Runsubtests are the standard Go style. ExampleXxxfunctions with// Output:are documentation that’s checked bygo test.BenchmarkXxx(b *testing.B)withfor b.Loop()measures speed; run with-bench.
You now have every tool you need. In the final lesson, you’ll combine them in a real project.
Finished this lesson?
Your progress is saved in this browser only.