Level: IntermediateGo Lang

Go Table-Driven Tests and Benchmarks Explained

8 min read
Go table-driven tests featured image: named cases, subtests and a benchmark

Go table-driven tests let you check many inputs with one short piece of test code. In this post, you will learn how to list cases in a slice. You will also run each one as a subtest and read the results. Then we will add a benchmark, so you can measure speed with real numbers.

This lesson builds on Go unit testing for beginners, where you wrote your first test. We also use slices and structs, which you met in Go slices and arrays and Go structs explained. Because of that, the code here should feel familiar. However, every new idea is explained step by step.

What Are Go Table-Driven Tests?

In short, Go table-driven tests keep all test cases in a list, called a table. Each row holds a name, the input and the result you expect. Then one loop runs every row through the same check. As a result, the test code stays short even when the table grows.

Think of a teacher with an answer sheet. The teacher keeps one marking process and one sheet of questions with answers. So if you add a question, the process stays the same.

Go developers love this style. In fact, the Go team itself uses it all over the standard library. As a result, you will see it in almost every open source Go project. For that reason, learning Go table-driven tests early will also help you read other people’s code.

Why Go Table-Driven Tests Matter

Without a table, people copy and paste a test function again and again. As a result, the file quickly becomes messy. So here is what Go table-driven tests fix.

  • Less repeated code: the check is written once, and the data changes.
  • Easy to add cases: a new edge case is one new line.
  • Clear failures: each case has a name, so you see exactly which one broke.
  • Better coverage: seeing all cases together helps you spot what is missing.
  • Easy review: teammates can read the table like a list of rules.

Because of this, tables are the standard way to test pure functions in Go. A pure function is one that returns the same result for the same input and changes nothing outside itself. Therefore, it is the easiest kind of code to put in a table.

How Go Table-Driven Tests Work

In Go table-driven tests, you first describe each case as a struct. After that, you put the structs in a slice. Then you loop over the slice and call t.Run with the case name. Finally, inside each subtest you compare the real result with the wanted one and call t.Errorf when they differ.

Go Table-Driven Tests diagram showing a table of named cases feeding one loop that runs subtests
A table of named cases feeds one loop. Each row becomes a subtest that calls the function, compares the result and reports a pass or fail.

However, a failed row does not stop the others. As a result, one run shows you every broken case at once.

The Parts of a Test Table

A table needs only three kinds of fields. So the table below lists them, and it adds a short example for each.

FieldPurposeExample
nameNames the subtest"extra spaces"
inputValue passed to the function" Go is fun "
wantResult you expect"go-is-fun"

Sometimes you also add wantErr bool when the function can return an error. Meanwhile, keep the struct small so the table stays easy to read. For example, a function that parses a date would have one row for a good date and one row for “31 February”, with wantErr set to true.

Subtests with t.Run

The t.Run function creates a named subtest. Because of this, failure messages show the exact case, such as TestMake/punctuation. You can also run a single case with the -run flag, which saves time when you debug.

Go Table-Driven Tests vs Separate Test Functions

You can write one test function per case, or you can write one table. Both work, but they feel different, as the table below shows. For example, adding a tenth case to a table takes seconds.

FeatureTable-drivenSeparate functions
Adding a caseOne new lineA new function
Repeated codeVery littleA lot
Failure messageShows the case nameShows the function name
Run one case-run Test/name-run TestName
Best forMany inputs, one ruleCases with very different setup
Go Table-Driven Tests diagram comparing a table with separate test functions
Table-driven tests share one check across many rows, while separate test functions repeat the check for every case.

So when should you use which? Use a table when the steps are the same and only the data changes. On the other hand, use separate functions when each case needs its own setup.

Go Table-Driven Tests Hands-On: Test a Slug Function

Now let’s test a small function that turns a title into a URL slug. For example, it turns “Hello World” into “hello-world”. To do this, it lowercases the text, keeps letters and digits, and joins words with dashes.

Step 1: The Function

First, here is the code that we want to test.

package slug

import (
	"strings"
	"unicode"
)

// Make turns a title into a URL-friendly slug.
func Make(title string) string {
	var b strings.Builder
	lastDash := true // avoids a leading dash
	for _, r := range strings.ToLower(title) {
		if unicode.IsLetter(r) || unicode.IsDigit(r) {
			b.WriteRune(r)
			lastDash = false
		} else if !lastDash {
			b.WriteByte('-')
			lastDash = true
		}
	}
	return strings.TrimSuffix(b.String(), "-")
}

Step 2: The Table-Driven Test

Next, we write the test in a file named slug_test.go. Each row is one scenario. Also, we include tricky ones, such as an empty string.

package slug

import "testing"

func TestMake(t *testing.T) {
	tests := []struct {
		name  string
		input string
		want  string
	}{
		{"simple words", "Hello World", "hello-world"},
		{"extra spaces", "  Go   is  fun  ", "go-is-fun"},
		{"punctuation", "Go: Tables & Tests!", "go-tables-tests"},
		{"digits kept", "Top 10 Go Tips", "top-10-go-tips"},
		{"empty string", "", ""},
		{"only symbols", "!!!", ""},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := Make(tt.input)
			if got != tt.want {
				t.Errorf("Make(%q) = %q, want %q", tt.input, got, tt.want)
			}
		})
	}
}

Let’s walk through the key lines. First, the anonymous struct slice is the table. Then the for loop visits each row, and t.Run starts a subtest named after the row. Finally, t.Errorf reports the input, the real result and the wanted result, so you can fix the bug quickly.

Step 3: Run the Tests

Now run go test -v. As a result, you should see the real output below.

=== RUN   TestMake
=== RUN   TestMake/simple_words
=== RUN   TestMake/extra_spaces
=== RUN   TestMake/punctuation
=== RUN   TestMake/digits_kept
=== RUN   TestMake/empty_string
=== RUN   TestMake/only_symbols
--- PASS: TestMake (0.00s)
    --- PASS: TestMake/simple_words (0.00s)
    --- PASS: TestMake/extra_spaces (0.00s)
    --- PASS: TestMake/punctuation (0.00s)
    --- PASS: TestMake/digits_kept (0.00s)
    --- PASS: TestMake/empty_string (0.00s)
    --- PASS: TestMake/only_symbols (0.00s)
PASS

Notice that Go replaces spaces in case names with underscores. Next, let’s see a failure by changing one wanted value. For example, if you expect go-tables-and-tests, the output points straight to the broken row.

--- FAIL: TestMake (0.00s)
    --- FAIL: TestMake/punctuation (0.00s)
        slug_test.go:22: Make("Go: Tables & Tests!") = "go-tables-tests", want "go-tables-and-tests"
FAIL

To run only one case, type go test -v -run "TestMake/extra". Also, go test -cover shows the share of code your tests touch. In our case, it reports 100.0% of statements, because every branch has a row.

Benchmarks: Measure Speed in Go

A benchmark measures how fast a function runs. Benchmark names start with Benchmark and take a *testing.B. Because speed varies, Go decides how many times to loop and stores that number in b.N.

func BenchmarkMake(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Make("Go: Tables & Tests for Beginners")
	}
}

Run it with go test -bench=. -benchmem -run=^$. The -run=^$ part skips normal tests, so only the benchmark runs. Then you will see output like the line below from our machine.

BenchmarkMake-2   	 3075823	       492.2 ns/op	      88 B/op	       4 allocs/op

Let’s read it from left to right. First, the function ran about 3 million times. Then each call took roughly 492 nanoseconds, used 88 bytes and made 4 memory allocations. Your numbers will differ, because they depend on your computer. However, the pattern is what matters: compare results before and after a change on the same machine.

Common Mistakes with Go Table-Driven Tests

  • Missing case names: unnamed cases make failures hard to find. So always fill the name field in every Go table-driven tests file you write.
  • Only happy paths: bugs hide in empty, huge and odd inputs. Therefore, add edge cases to every table.
  • Using the loop variable in parallel tests: older Go versions shared it between subtests. Since Go 1.22 each loop step has its own copy, but check your go.mod version.
  • Giant tables with long setup: the table becomes hard to read. Instead, split cases into groups.
  • Benchmarking once: one run is noisy. So repeat with -count=5 and compare the results.

Best Practices for Go Table-Driven Tests

  • Use descriptive names, because they act as living documentation.
  • Put edge cases first or last, so reviewers can find them quickly.
  • Print the input in the failure message, since it saves debugging time.
  • Keep one assertion style, because it makes every case read the same way.
  • **Run go test -race in CI**, because it also catches hidden data races.
  • Benchmark only hot code, since measuring everything wastes time.

Practice Task

To practise Go table-driven tests, write a function IsPalindrome(s string) bool that ignores case and spaces. Then create a table with at least six cases. Good examples are “Level”, “A man a plan a canal Panama” and an empty string.

Hint: build a cleaned slice of runes first. After that, compare it with its reverse. Finally, add a benchmark and compare a short string with a long one.

Official Resources

These pages explain the testing package, and they also describe the table-driven style in detail.

Quick Recap

  • Go table-driven tests keep every case in a slice of structs.
  • One loop with t.Run turns each row into a named subtest.
  • A failed row does not stop the other rows.
  • Use -run, -cover and -v to control and inspect a test run.
  • Benchmarks use b.N and report time, bytes and allocations per call.
  • Add edge cases such as empty strings and symbols to every table.

What’s Next?

By now, you can test pure functions with confidence. However, most real services also have HTTP handlers. So next, we will test full handlers without starting a real server, using the httptest package.

Next up: Go httptest for testing HTTP handlers