Programming languages · Intermediate · 26 min
Test Go code with table tests, fuzzing and benchmarks
By Padding · Updated 18 Nov 2026
Debian (golang:1.27 image) · Go 1.27.4
You will test a Go 1.27 phone-number normaliser with table-driven subtests, helpers, temporary folders and golden files, measure its coverage, let the fuzzer find a crash and keep it as a regression test, then prove an optimisation with b.Loop benchmarks and benchstat.
On this page
Go ships its test runner, coverage tool, fuzzer and benchmark harness in the go command and the testing package. You do not install a framework, and the same go test command runs all four. What you do need is a habit for each: tables for the cases you can think of, a fuzzer for the ones you cannot, and benchmarks with enough runs to tell a real speed-up from noise.
The code under test is a phone-number normaliser. People type numbers in many shapes: +234 803 123 4567, 0803-123-4567, (0805) 555 0199. Contact lists exported from phones in Nigeria, Ghana or Kenya are full of such variations, and an SMS gateway wants one form, E.164, such as +2348031234567. The first version you write works for ordinary input, hides one crash and allocates more than it needs to. The tests find both problems.
You build the package in ~/phone-demo. Each kind of test lives in its own file, so by the end the folder holds a small but complete test suite you can copy patterns from.
Step 1 · Create the module and the normaliser
Make the project folder and a module for it:
mkdir -p ~/phone-demo/testdata
cd ~/phone-demo
go mod init example.com/phoneCreate phone.go. Normalise drops the separators people type, keeps a leading +, turns a 00 prefix into +, and treats a leading 0 as a national number in the default country (234, Nigeria). NormaliseFile cleans a whole file of numbers, one per line:
cat > phone.go <<'GO'
// Package phone turns phone numbers as people type them into E.164 form.
package phone
import (
"errors"
"fmt"
"os"
"strings"
)
// ErrInvalid is returned for input that is not a usable phone number.
var ErrInvalid = errors.New("invalid phone number")
// DefaultCountry is the calling code used for numbers written in national
// form, such as 0803 123 4567.
var DefaultCountry = "234"
// Normalise returns raw in E.164 form, such as +2348031234567.
func Normalise(raw string) (string, error) {
digits := ""
plus := false
for i, r := range raw {
switch {
case r >= '0' && r <= '9':
digits += string(r)
case r == '+' && i == 0:
plus = true
case r == ' ', r == '-', r == '.', r == '(', r == ')':
// separators people type; drop them
default:
return "", fmt.Errorf("%w: unexpected %q in %q", ErrInvalid, r, raw)
}
}
switch {
case plus:
// already international
case strings.HasPrefix(digits, "00"):
digits = digits[2:]
case digits[0] == '0':
digits = DefaultCountry + digits[1:]
default:
return "", fmt.Errorf("%w: no country code in %q", ErrInvalid, raw)
}
if len(digits) < 8 || len(digits) > 15 {
return "", fmt.Errorf("%w: %d digits in %q", ErrInvalid, len(digits), raw)
}
return "+" + digits, nil
}
// NormaliseFile reads one number per line from src and writes the
// normalised form of each valid one to dst. Blank lines are skipped.
// It returns how many lines it rejected.
func NormaliseFile(src, dst string) (rejected int, err error) {
in, err := os.ReadFile(src)
if err != nil {
return 0, err
}
var out strings.Builder
for line := range strings.Lines(string(in)) {
line = strings.TrimSpace(line)
if line == "" {
continue
}
n, err := Normalise(line)
if err != nil {
rejected++
continue
}
out.WriteString(n + "\n")
}
return rejected, os.WriteFile(dst, []byte(out.String()), 0o644)
}
GO
gofmt -l .
go vet ./...E.164 numbers have at most 15 digits, which is where the upper limit comes from. strings.Lines yields each line of a string with its newline, which TrimSpace removes.
Check it worked
go mod init prints go: creating new go.mod: module example.com/phone. gofmt -l . and go vet ./... print nothing, which means the file is formatted and vet found nothing suspicious.
Step 2 · Write a table-driven test with subtests
A table test lists cases as data and runs the same checks over each. t.Run turns every row into a named subtest, so a failure names the case and you can rerun one row on its own. Create phone_test.go:
cat > phone_test.go <<'GO'
package phone
import (
"errors"
"testing"
)
func TestNormalise(t *testing.T) {
tests := []struct {
name string
raw string
want string
wantErr bool
}{
{name: "international with spaces", raw: "+234 803 123 4567", want: "+2348031234567"},
{name: "national form", raw: "0803 123 4567", want: "+2348031234567"},
{name: "brackets and dashes", raw: "(0803) 123-4567", want: "+2348031234567"},
{name: "dots", raw: "0803.123.4567", want: "+2348031234567"},
{name: "double zero prefix", raw: "00 44 20 7946 0958", want: "+442079460958"},
{name: "letters", raw: "0803 CALL ME", wantErr: true},
{name: "plus in the middle", raw: "0803+1234567", wantErr: true},
{name: "no country code", raw: "803 123 4567", wantErr: true},
{name: "too short", raw: "0803", wantErr: true},
{name: "too long", raw: "+1234567890123456", wantErr: true},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := Normalise(tc.raw)
if tc.wantErr {
if !errors.Is(err, ErrInvalid) {
t.Fatalf("Normalise(%q) error = %v, want ErrInvalid", tc.raw, err)
}
return
}
if err != nil {
t.Fatalf("Normalise(%q) unexpected error: %v", tc.raw, err)
}
if got != tc.want {
t.Errorf("Normalise(%q) = %q, want %q", tc.raw, got, tc.want)
}
})
}
}
GO
go test -v ./...The error cases check errors.Is(err, ErrInvalid) rather than the message text, so you can reword messages without breaking tests. t.Fatalf stops the current subtest; t.Errorf records a failure and carries on. Inside t.Run, a failure stops only that row, and the other rows still run.
Run a single row. Go replaces the spaces in a subtest name with underscores, and the -run pattern matches TestName/SubtestName:
go test -run 'TestNormalise/double_zero' -v ./...Check it worked
The first run prints === RUN TestNormalise/international_with_spaces and a --- PASS line for each of the ten rows, then ok example.com/phone. The second run lists only TestNormalise/double_zero_prefix. If you change one want value to something wrong, the failure line names that row and shows the input, the result and what you expected.
Step 3 · Add helpers, cleanup and testdata files
Three tools from the testing package keep larger tests tidy:
t.Helper()marks a function as a test helper, so a failure inside it is reported at the line that called it, not inside the helper.t.Cleanup(f)runsfwhen the test finishes, pass or fail. Use it to undo anything the test changed.t.TempDir()returns a new empty folder that Go deletes after the test.
The testdata folder is for fixture files. The go tool ignores it when it looks for packages, and tests run with the package folder as their working directory, so a relative path such as testdata/contacts.txt always works. Create an input file and a golden file that holds the exact output you expect:
cat > testdata/contacts.txt <<'TXT'
+234 803 123 4567
0803-123-4567
(0805) 555 0199
00 233 24 123 4567
not a number
0803 1
TXT
cat > testdata/contacts.golden <<'TXT'
+2348031234567
+2348031234567
+2348055550199
+233241234567
TXTNow create file_test.go with two helpers and two tests:
cat > file_test.go <<'GO'
package phone
import (
"os"
"path/filepath"
"testing"
)
// withCountry sets DefaultCountry for one test and restores it afterwards.
func withCountry(t *testing.T, code string) {
t.Helper()
old := DefaultCountry
DefaultCountry = code
t.Cleanup(func() { DefaultCountry = old })
}
// readFile returns a file's contents or stops the test.
func readFile(t *testing.T, path string) string {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
return string(data)
}
func TestNormaliseGhana(t *testing.T) {
withCountry(t, "233")
got, err := Normalise("024 123 4567")
if err != nil {
t.Fatal(err)
}
if want := "+233241234567"; got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestNormaliseFile(t *testing.T) {
dst := filepath.Join(t.TempDir(), "clean.txt")
rejected, err := NormaliseFile(filepath.Join("testdata", "contacts.txt"), dst)
if err != nil {
t.Fatal(err)
}
if rejected != 2 {
t.Errorf("rejected = %d, want 2", rejected)
}
got := readFile(t, dst)
want := readFile(t, filepath.Join("testdata", "contacts.golden"))
if got != want {
t.Errorf("output differs from the golden file\ngot:\n%s\nwant:\n%s", got, want)
}
}
GO
go test -v ./...Go runs test files in file-name order, so file_test.go runs before phone_test.go. TestNormaliseGhana switches the default country to 233, and TestNormalise still expects 234. It passes only because t.Cleanup put the old value back. Because DefaultCountry is a package variable, do not mark tests that change it with t.Parallel(); parallel tests would see each other's value.
Check it worked
go test -v now shows TestNormaliseGhana, TestNormaliseFile and the ten TestNormalise subtests passing. The blank line in contacts.txt is skipped, and the last two lines are the two rejected ones. Nothing is left behind in your folder: the clean.txt file lived in a temporary folder that Go removed when the test ended.
Step 4 · Measure coverage
Coverage tells you which statements the tests ran. A low number points at untested paths; a high number does not prove the tests check the right things. Get the summary, then write a profile and list coverage per function:
go test -cover ./...
go test -coverprofile=cover.out ./...
go tool cover -func=cover.outTo see the source with covered lines in one colour and missed lines in another, write an HTML report and open cover.html in a browser:
go tool cover -html=cover.out -o cover.htmlCheck it worked
The first command prints a line like ok example.com/phone 0.004s coverage: 96.4% of statements; your figure may differ slightly if you changed the code. go tool cover -func lists Normalise and NormaliseFile with a percentage each and a total: line. Normalise shows 100% and NormaliseFile a little less, because no test feeds it a file that does not exist. In cover.html that return 0, err line is marked as not covered. Every line of Normalise is covered, yet the next step shows it can still crash: coverage counts lines that ran, not inputs that were tried.
Step 5 · Let the fuzzer find a crash
A fuzz test is a function named FuzzXxx that takes *testing.F. You give it seed inputs with f.Add, and a target function that checks properties that must hold for any input. With -fuzz, Go mutates the seeds and keeps feeding new inputs to the target until something fails or the time runs out. Without -fuzz, go test runs only the seeds, as ordinary test cases.
The properties here: odd input may be rejected, but it must never panic; any accepted result is + followed by 8 to 15 digits; and normalising a result again returns it unchanged. Create fuzz_test.go:
cat > fuzz_test.go <<'GO'
package phone
import (
"strings"
"testing"
)
func FuzzNormalise(f *testing.F) {
for _, seed := range []string{
"+234 803 123 4567",
"0803-123-4567",
"(0805) 555 0199",
"00 233 24 123 4567",
"0803 CALL ME",
} {
f.Add(seed)
}
f.Fuzz(func(t *testing.T, raw string) {
got, err := Normalise(raw)
if err != nil {
return // rejecting odd input is fine; crashing is not
}
if !strings.HasPrefix(got, "+") || strings.Trim(got[1:], "0123456789") != "" {
t.Fatalf("Normalise(%q) = %q, want + and digits only", raw, got)
}
if n := len(got) - 1; n < 8 || n > 15 {
t.Fatalf("Normalise(%q) = %q has %d digits", raw, got, n)
}
again, err := Normalise(got)
if err != nil || again != got {
t.Fatalf("Normalise(%q) = %q, %v; want it unchanged", got, again, err)
}
})
}
GO
go test -run FuzzNormalise -v ./...The seeds pass. Now start the fuzzer, with a time limit so it cannot run forever. -run='^$' skips the ordinary tests, and the -fuzz pattern must match exactly one fuzz test:
go test -run='^$' -fuzz='^FuzzNormalise$' -fuzztime=60sThe fuzzer uses every CPU core by default. On a modest laptop you can add -parallel=2 to keep the machine usable while it runs.
Check it worked
Usually within a second or two the run stops with --- FAIL: FuzzNormalise and a panic: runtime error: index out of range [0] with length 0. The stack trace points at the case digits[0] == '0': line in phone.go. The output ends with something like:
Failing input written to testdata/fuzz/FuzzNormalise/5838cdfae7b16cde
To re-run:
go test -run=FuzzNormalise/5838cdfae7b16cde
FAILThe name after FuzzNormalise/ is a hash and differs on your machine. The bug: input with no digits at all, such as an empty string, () or a single space, gets past the character loop, and digits[0] reads from an empty string.
Step 6 · Keep the crash as a regression test
Look at the file the fuzzer wrote:
ls testdata/fuzz/FuzzNormalise/
cat testdata/fuzz/FuzzNormalise/*The file starts with go test fuzz v1, followed by the input as a Go literal, for example string("") for the empty string. Every file in testdata/fuzz/FuzzNormalise now runs as a seed whenever anyone runs plain go test, so commit the folder with your code. That alone makes the crash a regression test.
Also write the case down as a named test, so the next reader of the code sees the rule in words. Append it to phone_test.go, which already imports errors and testing, and run it:
cat >> phone_test.go <<'GO'
func TestNormaliseNoDigits(t *testing.T) {
for _, raw := range []string{"", " ", "()", "- -"} {
if _, err := Normalise(raw); !errors.Is(err, ErrInvalid) {
t.Errorf("Normalise(%q) error = %v, want ErrInvalid", raw, err)
}
}
}
GOgo test -run TestNormaliseNoDigits ./...It fails with the same panic. Now fix Normalise by rejecting input with no digits before the code reads the first one. Replace phone.go with this version; the only change is the new if digits == "" block:
cat > phone.go <<'GO'
// Package phone turns phone numbers as people type them into E.164 form.
package phone
import (
"errors"
"fmt"
"os"
"strings"
)
// ErrInvalid is returned for input that is not a usable phone number.
var ErrInvalid = errors.New("invalid phone number")
// DefaultCountry is the calling code used for numbers written in national
// form, such as 0803 123 4567.
var DefaultCountry = "234"
// Normalise returns raw in E.164 form, such as +2348031234567.
func Normalise(raw string) (string, error) {
digits := ""
plus := false
for i, r := range raw {
switch {
case r >= '0' && r <= '9':
digits += string(r)
case r == '+' && i == 0:
plus = true
case r == ' ', r == '-', r == '.', r == '(', r == ')':
// separators people type; drop them
default:
return "", fmt.Errorf("%w: unexpected %q in %q", ErrInvalid, r, raw)
}
}
if digits == "" {
return "", fmt.Errorf("%w: no digits in %q", ErrInvalid, raw)
}
switch {
case plus:
// already international
case strings.HasPrefix(digits, "00"):
digits = digits[2:]
case digits[0] == '0':
digits = DefaultCountry + digits[1:]
default:
return "", fmt.Errorf("%w: no country code in %q", ErrInvalid, raw)
}
if len(digits) < 8 || len(digits) > 15 {
return "", fmt.Errorf("%w: %d digits in %q", ErrInvalid, len(digits), raw)
}
return "+" + digits, nil
}
// NormaliseFile reads one number per line from src and writes the
// normalised form of each valid one to dst. Blank lines are skipped.
// It returns how many lines it rejected.
func NormaliseFile(src, dst string) (rejected int, err error) {
in, err := os.ReadFile(src)
if err != nil {
return 0, err
}
var out strings.Builder
for line := range strings.Lines(string(in)) {
line = strings.TrimSpace(line)
if line == "" {
continue
}
n, err := Normalise(line)
if err != nil {
rejected++
continue
}
out.WriteString(n + "\n")
}
return rejected, os.WriteFile(dst, []byte(out.String()), 0o644)
}
GO
go test -v ./...Check it worked
The full run passes. In the verbose output, FuzzNormalise now lists one subtest per seed and one named after the hash file, such as FuzzNormalise/5838cdfae7b16cde, and TestNormaliseNoDigits passes. Run the fuzzer again for half a minute if you like; it now ends with PASS and a line like fuzz: elapsed: 30s, execs: .... Inputs it found interesting along the way are kept in Go's cache, not in your folder, so they do not clutter the repository.
Step 7 · Write a benchmark with b.Loop
A benchmark is a function named BenchmarkXxx that takes *testing.B. Since Go 1.24 the recommended form is for b.Loop() { ... }: Go runs the loop body as many times as it needs for a stable timing, does not count the setup before the loop, and stops the compiler from optimising away calls inside the loop. Create bench_test.go:
cat > bench_test.go <<'GO'
package phone
import "testing"
func BenchmarkNormalise(b *testing.B) {
inputs := []string{"+234 803 123 4567", "(0805) 555-0199", "00 233 24 123 4567"}
for b.Loop() {
for _, raw := range inputs {
if _, err := Normalise(raw); err != nil {
b.Fatal(err)
}
}
}
}
GOOne run is not enough to compare: timings wobble with whatever else the machine is doing. Run the benchmark six times and save the result. -benchmem adds bytes and allocations per operation, and -run='^$' skips the tests:
go test -run='^$' -bench=Normalise -benchmem -count=6 > old.txt
cat old.txtClose other heavy programs while benchmarks run, and on a laptop keep it plugged in; power saving can slow the processor between runs.
Check it worked
old.txt holds a header with goos, goarch, pkg and cpu lines, then six lines starting BenchmarkNormalise- followed by your core count. Each line shows an iteration count, ns/op, B/op and allocs/op. Each operation normalises three numbers. A check run while writing this tutorial measured 76 allocations and 560 bytes per operation; the exact count can shift between Go releases and platforms, but it will be dozens, because the digits += string(r) line builds a new string for every digit.
Step 8 · Optimise and compare with benchstat
Rewrite Normalise so it collects digits in a fixed-size array on the stack and builds the result once. The array holds 17 digits, the 15 that E.164 allows plus a 00 prefix; anything longer is rejected straight away. Replace phone.go:
cat > phone.go <<'GO'
// Package phone turns phone numbers as people type them into E.164 form.
package phone
import (
"errors"
"fmt"
"os"
"strings"
)
// ErrInvalid is returned for input that is not a usable phone number.
var ErrInvalid = errors.New("invalid phone number")
// DefaultCountry is the calling code used for numbers written in national
// form, such as 0803 123 4567.
var DefaultCountry = "234"
// maxRawDigits is the most digits Normalise reads: the 15 that E.164
// allows, plus a 00 prefix.
const maxRawDigits = 17
// Normalise returns raw in E.164 form, such as +2348031234567.
func Normalise(raw string) (string, error) {
var buf [maxRawDigits]byte
n := 0
plus := false
for i, r := range raw {
switch {
case r >= '0' && r <= '9':
if n == len(buf) {
return "", fmt.Errorf("%w: too many digits in %q", ErrInvalid, raw)
}
buf[n] = byte(r)
n++
case r == '+' && i == 0:
plus = true
case r == ' ', r == '-', r == '.', r == '(', r == ')':
// separators people type; drop them
default:
return "", fmt.Errorf("%w: unexpected %q in %q", ErrInvalid, r, raw)
}
}
digits := buf[:n]
if len(digits) == 0 {
return "", fmt.Errorf("%w: no digits in %q", ErrInvalid, raw)
}
prefix := ""
switch {
case plus:
// already international
case len(digits) >= 2 && digits[0] == '0' && digits[1] == '0':
digits = digits[2:]
case digits[0] == '0':
prefix = DefaultCountry
digits = digits[1:]
default:
return "", fmt.Errorf("%w: no country code in %q", ErrInvalid, raw)
}
total := len(prefix) + len(digits)
if total < 8 || total > 15 {
return "", fmt.Errorf("%w: %d digits in %q", ErrInvalid, total, raw)
}
var b strings.Builder
b.Grow(1 + total)
b.WriteByte('+')
b.WriteString(prefix)
b.Write(digits)
return b.String(), nil
}
// NormaliseFile reads one number per line from src and writes the
// normalised form of each valid one to dst. Blank lines are skipped.
// It returns how many lines it rejected.
func NormaliseFile(src, dst string) (rejected int, err error) {
in, err := os.ReadFile(src)
if err != nil {
return 0, err
}
var out strings.Builder
for line := range strings.Lines(string(in)) {
line = strings.TrimSpace(line)
if line == "" {
continue
}
n, err := Normalise(line)
if err != nil {
rejected++
continue
}
out.WriteString(n + "\n")
}
return rejected, os.WriteFile(dst, []byte(out.String()), 0o644)
}
GO
go test ./...
go test -run='^$' -fuzz='^FuzzNormalise$' -fuzztime=20sA faster function is worthless if it is wrong. The tests, the golden file and the saved fuzz crash all run against the new code, and a short fuzz run checks the rewrite against inputs nobody listed. Now benchmark the new version the same way:
go test -run='^$' -bench=Normalise -benchmem -count=6 > new.txtbenchstat compares two sets of results and says whether a difference is statistically meaningful. go get -tool records it in go.mod at a pinned version, so everyone on the project runs the same one through go tool. golang.org/x/perf has no tagged releases, so the version is a dated pseudo-version:
go get -tool golang.org/x/perf/cmd/benchstat@v0.0.0-20261117185222-4febdb082b2c
go tool benchstat old.txt new.txtCheck it worked
go test ./... prints ok example.com/phone and the fuzz run ends with PASS. go.mod now has a tool golang.org/x/perf/cmd/benchstat line. benchstat prints three tables, for sec/op, B/op and allocs/op, each with an old.txt column, a new.txt column and a vs base column. The allocs/op table from the check run looked like this (benchstat prints every value in a row to the precision of the smallest, hence 76.000):
│ old.txt │ new.txt │
│ allocs/op │ allocs/op vs base │
Normalise-8 76.000 ± 0% 3.000 ± 0% -96.05% (p=0.002 n=6)Going from 76 to 3 allocations is (3 − 76) ÷ 76, the −96.05% shown; your counts and percentage may differ slightly. A negative percentage with a small p value (below 0.05) is a real improvement. If benchstat prints ~ instead of a percentage, the difference is within the noise and you have not shown a speed-up. Allocations are exact counts, so they are the most reliable column; the sec/op change depends on your machine.
Step 9 · Clean up
Your test suite is now four test files and the saved crash in testdata/fuzz: phone_test.go (table and subtests, plus the named regression test), file_test.go (helpers, t.Cleanup, t.TempDir and golden files), fuzz_test.go and bench_test.go. Copy the patterns you want into your own projects, then remove the demo folder and the inputs the fuzzer cached:
cd ~
rm -rf ~/phone-demo
go clean -fuzzcacheCheck it worked
ls ~/phone-demo reports that the folder does not exist. go clean -fuzzcache prints nothing; it removes the cached fuzz inputs for every project, but never the testdata/fuzz files in your repositories, which are the ones that matter.
Next steps
- Return errors that tests can check with
errors.Isin handle errors the Go way with wrapping and errors.Is. - Test HTTP handlers without opening a port with
httptest, in write your first Go web server. - Compare Go's approach with Python's in test Python code with pytest.
- New to the toolchain? Start with Hello World in Go.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials