Skip to content
T2Run
Esc
  • RunPad Text Editor
    A Notepad++-style editor in your browser: tabs, split view, compare, 30 languages, JSON/XML/YAML tools.
    Text
  • Diff Checker
    Compare two texts or files side by side and see every added, removed and changed line.
    Text
  • JSON Beautifier
    Format, validate, sort and minify JSON with precise error locations.
    JSON & Data
  • Face Map Studio
    Map, chart and document botulinum toxin treatments on 3D face maps of your patient’s photos, with guided clinical photography.
    Health & Clinic
  • Photo Editor & Passport Photo Maker
    Edit photos with pro adjustments, filters, crop, text and background removal — plus passport photos for 25+ countries.
    Image
  • Image Resizer
    Batch resize photos by pixels or percent and export to JPG, PNG or WebP.
    Image
  • JSON Validator
    Check if JSON is valid and see the exact line and column of any error.
    JSON & Data
  • JSON Minifier
    Remove whitespace to make JSON compact, and see how many bytes you saved.
    JSON & Data

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:

textutil.go
// 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:

textutil_test.go
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:

Terminal
go test
Output
PASS
ok  	example.com/textutil	0.207s

The 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.Errorf reports a failure and continues the test.
  • t.Fatalf reports a failure and stops this test immediately. Use it when continuing makes no sense, such as after an unexpected error.
  • _test.go files are only compiled by go 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:

textutil_test.go
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:

Terminal
go test -v
Output
=== 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.207s

What a failure looks like

Suppose someone “simplifies” IsPalindrome and accidentally removes strings.ToLower. Running the tests catches it straight away:

Output
--- 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.424s

The 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:

Terminal
go test -run TestIsPalindrome/mixed -v
Output
=== RUN   TestIsPalindrome
=== RUN   TestIsPalindrome/mixed_case
--- PASS: TestIsPalindrome (0.00s)
    --- PASS: TestIsPalindrome/mixed_case (0.00s)
PASS
ok  	example.com/textutil	0.198s

Example 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:

example_test.go
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:

Terminal
go test -cover
Output
PASS
coverage: 100.0% of statements
ok  	example.com/textutil	0.425s

To see exactly which lines are covered, write a profile and open it as a coloured HTML page:

Terminal
go test -coverprofile=cover.out
go tool cover -html=cover.out

High 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:

textutil_test.go
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:

Terminal
go test -bench . -run '^$'
Output
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.413s

Reverse 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 like strings.NewReader.
  • Run go test ./... to test every package in your module, and add -race to 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
textutil_test.go
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
percent_test.go
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.go files; test functions are func TestXxx(t *testing.T).
  • go test runs them; -v shows details, -run filters, -cover reports coverage.
  • Table-driven tests with t.Run subtests are the standard Go style.
  • ExampleXxx functions with // Output: are documentation that’s checked by go test.
  • BenchmarkXxx(b *testing.B) with for 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.