Explain it simply
Testing in plain language
A test is code that questions your code automatically: 'given this input, this output must come out'. Every time you change something, running go test tells you within seconds whether everything that used to work still works.
In Go, tests, benchmarks and fuzz tests all come with the testing package; there is nothing extra to install. A test checks whether code is correct, a benchmark measures how fast it is, and fuzzing generates thousands of random inputs to find the case you did not think of.
Problem → Why → Solution
The problem: it works on ASCII
You write Truncate to cut notification text to 20 characters. Trying it with "gopher" gives "gop", which looks right. Then a user types 'héllo' or Myanmar text and the notification shows broken ? characters. One correct sample output does not prove the code is correct.
func Truncate(s string, max int) string {
if len(s) <= max { // len counts BYTES, not characters
return s
}
return s[:max] // can cut a multi-byte character in half
}
// Truncate("gopher", 3) == "gop" looks fine
// Truncate("héllo", 2) == "h\xc3" invalid UTF-8: é is two bytesWhy tests are needed
A Go string is a sequence of bytes: é takes two bytes and a Myanmar letter takes three. s[:max] cuts by bytes, so it can split a character in the middle. Bugs like this never show up with inputs you pick yourself. A table of edge cases in a test, plus fuzzing with random inputs, catches it.
Core concept: the go test conventions
Test files are files ending in _test.go. A normal go build ignores them; only go test compiles them. go test finds every function shaped like func TestXxx(t *testing.T) in those files and runs each one. A test in the same package can exercise unexported functions, while an external test package such as total_test sees only the public API, just like a caller.
*testing.T has two ways to report a failure. t.Errorf marks the test failed and keeps going, so you see the results of later checks in the same run. t.Fatalf marks it failed and stops that test immediately; use it when continuing makes no sense, such as after failed setup. The standard Go shape is the table-driven test: loop over a slice of structs holding name, input and want, and run each case as a subtest with t.Run(tc.name, ...). Adding a case is one more line, and you can run a single case by name with go test -run 'TestTruncate/multi'.
Benchmarks look like func BenchmarkXxx(b *testing.B). The framework tunes b.N automatically, running the loop enough times to measure, and reports ns/op for one operation. Fuzz tests look like func FuzzXxx(f *testing.F): f.Add supplies seed inputs, and the function given to f.Fuzz checks a property that must hold for every input. A plain go test runs only the seeds; the -fuzz flag makes it keep generating new inputs.
| Command | What it does |
|---|---|
| go test ./... | runs tests in every package of the module |
| go test -run TestTruncate -v | runs matching tests with verbose output |
| go test -bench=. -benchmem | runs benchmarks and reports allocations |
| go test -fuzz=FuzzTruncate -fuzztime=30s | fuzzes one fuzz test for 30 seconds |
| go test -race -cover | runs with the race detector and coverage on |
- Test: are the chosen cases right?
- Benchmark: how fast is it?
- Fuzz: which input breaks it?
- Keep each fuzz find as a seed
Tests check what you expected; fuzzing finds what you did not. You need both.
General pattern
// file: name_test.go
func TestName(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := Func(tc.in); got != tc.want { t.Errorf("...") }
})
}
}
func BenchmarkName(b *testing.B) { for i := 0; i < b.N; i++ { Func(input) } }
func FuzzName(f *testing.F) {
f.Add(seed); f.Fuzz(func(t *testing.T, in Type) { /* check property */ })
}The name prefix (Test, Benchmark, Fuzz) and the parameter type (*testing.T, *testing.B, *testing.F) tell go test what to do with each function. All of them live in _test.go files.
Worked example: checking Truncate with a case table
The program below checks a Truncate that cuts by runes (Unicode characters), using the table-driven shape. It runs in main instead of under the test framework, so you can try it straight away with go run. The loop, the case struct and the got/want comparison are exactly what you would write in a _test.go file; the next section shows that version.
package main
import (
"fmt"
"unicode/utf8"
)
// Truncate shortens s to at most max characters (runes),
// never cutting a multi-byte character in half.
func Truncate(s string, max int) string {
if max <= 0 {
return ""
}
if utf8.RuneCountInString(s) <= max {
return s
}
return string([]rune(s)[:max])
}
func main() {
tests := []struct {
name string
in string
max int
want string
}{
{"shorter", "Go", 5, "Go"},
{"exact", "gopher", 6, "gopher"},
{"cut ascii", "gopher", 3, "gop"},
{"zero max", "gopher", 0, ""},
{"multi-byte", "héllo", 2, "hé"},
}
passed := 0
for _, tc := range tests {
got := Truncate(tc.in, tc.max)
status := "FAIL"
if got == tc.want {
status = "PASS"
passed++
}
fmt.Printf("%s %-10s Truncate(%q, %d) = %q\n",
status, tc.name, tc.in, tc.max, got)
}
fmt.Printf("%d/%d cases passed\n", passed, len(tests))
}Code breakdown
- Count characters, not bytes
if utf8.RuneCountInString(s) <= max {RuneCountInString is used instead of len(s), so é or a Myanmar letter counts as one character.
- Cut on rune boundaries
return string([]rune(s)[:max])The string becomes a []rune before slicing, so a character is never split, and then it is converted back to a string.
- The case table
{"multi-byte", "héllo", 2, "hé"},Each case is one line with a name, input, max and want. This multi-byte case is exactly the one that catches the bug from the problem section.
- Compare got with want
if got == tc.want {The heart of every test is comparing got with want. In the _test.go version, a mismatch calls t.Errorf instead.
- Readable report
fmt.Printf("%s %-10s Truncate(%q, %d) = %q\n",%q prints strings in quotes, so the empty string is clearly visible as "". A good failure message always includes the input, got and want.
PASS shorter Truncate("Go", 5) = "Go"
PASS exact Truncate("gopher", 6) = "gopher"
PASS cut ascii Truncate("gopher", 3) = "gop"
PASS zero max Truncate("gopher", 0) = ""
PASS multi-byte Truncate("héllo", 2) = "hé"
5/5 cases passedTest, benchmark and fuzz in a _test.go file
In a real project, Truncate lives in truncate.go and its tests sit beside it in truncate_test.go. The file below turns the table above into t.Run subtests and adds one benchmark and one fuzz test. The fuzz test does not check exact outputs; it checks three rules that must hold whatever the input is.
package text
import (
"strings"
"testing"
"unicode/utf8"
)
func TestTruncate(t *testing.T) {
tests := []struct {
name, in string
max int
want string
}{
{"cut ascii", "gopher", 3, "gop"},
{"multi-byte", "héllo", 2, "hé"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := Truncate(tc.in, tc.max); got != tc.want {
t.Errorf("Truncate(%q, %d) = %q, want %q", tc.in, tc.max, got, tc.want)
}
})
}
}
var sink string // keeps the result alive so the call is not optimised away
func BenchmarkTruncate(b *testing.B) {
s := strings.Repeat("héllo ", 100)
for i := 0; i < b.N; i++ {
sink = Truncate(s, 20)
}
}
func FuzzTruncate(f *testing.F) {
f.Add("héllo", 2)
f.Add("gopher", 3)
f.Fuzz(func(t *testing.T, s string, max int) {
if !utf8.ValidString(s) {
t.Skip() // the rules below only make sense for valid UTF-8
}
got := Truncate(s, max)
if !utf8.ValidString(got) {
t.Errorf("invalid UTF-8 output %q", got)
}
if !strings.HasPrefix(s, got) {
t.Errorf("%q is not a prefix of %q", got, s)
}
if max >= 0 && utf8.RuneCountInString(got) > max {
t.Errorf("got %d runes, max %d", utf8.RuneCountInString(got), max)
}
})
}The commands and the shape of their output look like this. Benchmark numbers differ from machine to machine, so treat them as a sample only. Run this fuzz test against the byte-slicing Truncate and the "héllo" seed fails at once, before any random input is generated. Even with that seed removed, the fuzzer finds a failing input within seconds, writes it as a file under testdata/fuzz/FuzzTruncate/, and prints the go test -run command that replays it. Commit that file and every plain go test reruns that input as a regression case.
$ go test -run TestTruncate -v
=== RUN TestTruncate
=== RUN TestTruncate/cut_ascii
=== RUN TestTruncate/multi-byte
--- PASS: TestTruncate (0.00s)
--- PASS: TestTruncate/cut_ascii (0.00s)
--- PASS: TestTruncate/multi-byte (0.00s)
PASS
$ go test -bench=Truncate -benchmem # sample numbers, yours will differ
BenchmarkTruncate-8 156607 22386 ns/op 2720 B/op 2 allocs/op
$ go test -fuzz=FuzzTruncate -fuzztime=30s-fuzz targets exactly one fuzz test
The pattern given to -fuzz must match exactly one fuzz test in the package. Also note that without -fuzztime, fuzzing keeps running until it finds a failure or you press Ctrl+C.
In real projects
In real projects
In Go teams, go test ./... is the basic gate for every pull request, usually run in CI together with go vet and -race. The testing package is deliberately minimal, and many projects use nothing but if statements and t.Errorf, with no assertion library at all.
- For code that reads input, such as parsers, validators and encoders, fuzz tests find panics and wrong results before they turn into security problems.
- Before sending a performance PR, run the benchmark before and after the change and compare ns/op and allocs/op. Run it several times so the numbers settle.
- When a bug report arrives, first add a table case that reproduces it, then fix the code, so the bug cannot quietly come back.
Common mistakes
Common testing mistakes
Testing only the happy path
A single test that Sum([]int{1, 2, 3}) == 6 says nothing about a nil slice, negative numbers or huge values. Give zero, empty, boundary and invalid inputs a row each in the table. For functions that return errors, add wantErr as a column too.
Using t.Fatalf in a loop and hiding the other cases
Calling t.Fatalf inside a loop without subtests stops the whole test at the first failure, so you never learn whether the other cases pass. Put each case in t.Run, or use t.Errorf.
Benchmarking code the compiler removed
If a benchmark loop never uses the result, the compiler may optimise the call away and report an impossibly fast ns/op. Store the result in a package-level variable. Go 1.24 and later also offer the for b.Loop() { ... } form, which guards against this.
Mini challenge
Mini challenge: test ParsePort, error cases included
Write ParsePort, which turns text such as "8080" into a TCP port number, and check it in table-driven style. Non-numeric text and values outside 1-65535 must be rejected with an error, and the table must check the kind of error with errors.Is.
- ParsePort(s string) (int, error) wraps the strconv.Atoi error with %w
- Values out of range return a wrapped ErrPortRange sentinel error
- The table includes boundaries (1, 65535, 0, 70000), non-numeric text and the empty string
- Print each case's result and the number of failures
package main
import (
"errors"
"fmt"
"strconv"
)
var ErrPortRange = errors.New("port out of range")
func ParsePort(s string) (int, error) {
// TODO: convert with strconv.Atoi and wrap its error using %w
// TODO: reject values outside 1-65535 with a wrapped ErrPortRange
return 0, nil
}
func main() {
cases := []struct {
in string
want int
wantErr error // nil means "expect success"
}{
// TODO: add boundary, invalid and empty-string cases
}
// TODO: loop, compare got/want and errors.Is(err, c.wantErr), count failures
_ = cases
fmt.Println("failures:", 0)
_ = strconv.ErrSyntax
}Expected: All seven cases print ok; 0 and 70000 show 'port out of range', "http" and "" show an 'invalid syntax' error, and the last line is failures: 0.
Show hint
errors.Is(nil, nil) is true and errors.Is(someErr, nil) is false, so the single check ok := got == c.want && errors.Is(err, c.wantErr) handles both success and error cases. The error from strconv.Atoi wraps strconv.ErrSyntax.
Show solution
package main
import (
"errors"
"fmt"
"strconv"
)
var ErrPortRange = errors.New("port out of range")
// ParsePort turns text such as "8080" into a TCP port number.
func ParsePort(s string) (int, error) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, fmt.Errorf("parse port %q: %w", s, err)
}
if n < 1 || n > 65535 {
return 0, fmt.Errorf("parse port %q: %w", s, ErrPortRange)
}
return n, nil
}
func main() {
cases := []struct {
in string
want int
wantErr error
}{
{"8080", 8080, nil},
{"1", 1, nil},
{"65535", 65535, nil},
{"0", 0, ErrPortRange},
{"70000", 0, ErrPortRange},
{"http", 0, strconv.ErrSyntax},
{"", 0, strconv.ErrSyntax},
}
failures := 0
for _, c := range cases {
got, err := ParsePort(c.in)
// errors.Is(nil, nil) is true, so success cases need no special branch
ok := got == c.want && errors.Is(err, c.wantErr)
if !ok {
failures++
fmt.Printf("FAIL ParsePort(%q) = %d, %v\n", c.in, got, err)
continue
}
fmt.Printf("ok ParsePort(%q) = %d, err=%v\n", c.in, got, err)
}
fmt.Println("failures:", failures)
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Tests are TestXxx(t *testing.T) functions in _test.go files, found and run by go test.
- Table-driven tests with t.Run make new cases cheap and let you run one case by name.
- Benchmarks run b.N times and report ns/op; the numbers depend on the machine.
- Fuzz tests check a property against random inputs and save any failure in testdata as a regression case.