Skip to content
Tutorials Center
My learning

Topics

Lesson 100 of 147 ยท Testing and Tooling

Table-Driven Tests and Testable Design

Learn table-driven tests in Go - subtests with t.Run, helpers, parallel cases, golden files, fakes behind interfaces, httptest handlers and a fake clock for time-dependent code.

After a few weeks of writing tests, a pattern shows up: the same function is called again and again with different inputs, and each call is followed by the same kind of check. Copying a test function twenty times is tedious, and when the check changes you have to fix twenty places. Go programmers solved this with a convention so common that it has a name: the table-driven test. You describe the cases as data (a slice of structs), then run one loop that checks them all.

This lesson builds on the basics of the testing package. You will write table tests with named subtests, add helpers that report the right line, run cases in parallel, compare output with golden files, and then look at the design side: how to shape code so that a database, a clock or an HTTP server can be replaced in a test. Benchmarks and fuzzing come next in the benchmarks lesson.

This site cannot run go test, so every runnable example here calls testing.Main from main with a tiny harness. The TestXxx functions are exactly what you would put in a _test.go file. In your own project you delete the harness and run go test -v.

The shape of a table test

A table test has three parts: a slice of anonymous structs that holds the inputs and the expected result, a for loop over it, and t.Run inside the loop to start a subtest named after the case. Here is a function that turns a title into a URL slug, together with its test:

Go A first table-driven test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Look at the output: every case is reported on its own line as TestSlug/simple, TestSlug/extra_spaces and so on. t.Run replaces spaces in the name with underscores so that the name can be used on a command line. That naming is the main benefit of subtests, because you can run just one case:

Terminal
go test -run 'TestSlug/punctuation'
go test -run 'TestSlug/digits|TestSlug/empty'

The part before the slash is a regular expression matched against the top-level test, and the part after it is matched against the subtest names. Without t.Run, a failing case would only tell you a line number in the loop, and you would have to guess which row was meant.

Why there is no tt := tt

Older Go code often starts the loop body with tt := tt. That line existed because, before Go 1.22, every iteration of a for loop shared one loop variable. A subtest that ran later (especially a parallel one) could see the variable after it had moved on. Since Go 1.22 each iteration has its own copy of tt (see for loops and closures), so the line is no longer needed. If you see it in an old codebase, it does no harm, and you can delete it.

Choosing fields for the table

The struct fields are whatever your function needs. Three habits make tables easy to read:

  • Put name first and make it describe the situation ("empty input", "negative balance"), not the number of the case.
  • Name the expected value want and the input in or args. Test failures then read the same way across the project.
  • Use a field for the error. If a function can fail, add wantErr bool, or better, wantErr error and compare with errors.Is. That way the table also documents which error each bad input produces.

You can also use a map[string]struct{...} with the case name as the key. The advantage is that duplicate names are impossible; the disadvantage is that map iteration order is random, so cases run in a different order each time. A slice keeps the order stable, which helps when you read the output.

Testing errors in a table

Here is a table with a wantErr column. The function parses a duration such as "90s" or "2m" into seconds, and the table includes failure cases:

Go Error cases in the table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Two details matter here. First, errors.Is(err, tt.wantErr) is true for the success rows because errors.Is(nil, nil) is true, so one comparison covers both the "no error expected" and the "this specific error expected" cases (see wrapping errors for how %w makes this work). Second, the error check uses t.Fatalf, which stops only this subtest. Checking got after an unexpected error would just produce a second, confusing failure.

Compare errors with errors.Is or errors.As, not by comparing err.Error() strings. A test that matches on message text breaks the day someone fixes a typo in the message.

Helpers and the right line number

When a failing check reports a line number, you want it to be the line in your test table, not a line inside a shared assertion function. Calling t.Helper() as the first statement of a helper tells the testing package to skip that function when it picks the line to print. Compare the two helpers below. Both are used from TestPrice, and the test is wrong on purpose so that you can see where each failure is reported:

Go t.Helper decides the reported line (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first message points at the line inside checkPlain (where t.Errorf is), which is useless: that line is the same for every failure. The second message points at the line in TestPrice that called checkHelper, which is exactly the check that failed. In the run above the plain helper reports main.go:13 (inside the helper), while the one with t.Helper() reports main.go:26 (the call in the test).

Helpers that set something up are also marked with t.Helper(), and they often register cleanup work with t.Cleanup. Cleanup functions run when the test and all its subtests have finished, in last-in, first-out order, even if the test failed:

Go
func newTestStore(t *testing.T) *Store {
	t.Helper()
	s, err := OpenStore(t.TempDir() + "/db.sqlite") // TempDir is removed automatically
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { s.Close() })
	return s
}

t.TempDir() gives every test its own empty directory that is deleted afterwards, and t.Setenv("KEY", "value") sets an environment variable and restores the old value at the end. Both save you from writing defer cleanup in every test.

Running cases in parallel

Table tests are a natural fit for t.Parallel(). A subtest that calls it pauses until its parent function has finished its own body, then runs at the same time as the other parallel subtests (the limit is set by -parallel, which defaults to GOMAXPROCS). Use it for cases that are slow and independent, such as ones that wait on a network or sleep.

Go Parallel subtests and t.Cleanup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The order in which parallel subtests finish is not guaranteed, so this example prints only the count at the end. Three rules keep parallel tests safe:

  • Capture nothing that changes. Because of Go 1.22 loop semantics, tc is safe to use inside the closure. If a case needs shared state, make it a local variable of the subtest.
  • Don't mix t.Parallel with t.Setenv or os.Chdir. They change process-wide state, so t.Setenv panics in a parallel test.
  • Check the race detector. Run go test -race ./... in CI; parallel tests are where data races hide (see data races).

Golden files

Some outputs are too big to write as string literals: a rendered HTML page, a formatted report, a JSON document with 40 fields. A golden file stores the expected output in testdata/ (the go tool ignores directories with that name when it builds packages). The test renders the output and compares it with the file; a flag rewrites the file when the change is intended:

Go
var update = flag.Bool("update", false, "rewrite golden files")

func TestReport(t *testing.T) {
	got := RenderReport(sampleOrders)

	golden := filepath.Join("testdata", "report.golden")
	if *update {
		if err := os.WriteFile(golden, got, 0o644); err != nil {
			t.Fatal(err)
		}
	}
	want, err := os.ReadFile(golden)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(got, want) {
		t.Errorf("output differs from %s; run: go test -run TestReport -update\ngot:\n%s", golden, got)
	}
}

After an intentional change, run go test -run TestReport -update, then look at git diff testdata/ to review exactly what changed before you commit. That review step is the whole point: a golden file only protects you if a human reads the diff.

The next example does the same thing inside a temporary directory so that it can run on this site. It writes the "golden" file first, then compares the output of two versions of the renderer:

Go A golden-file test in a temp directory (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The second subtest fails and prints both versions: the padded x 3 against the stored x3. Golden tests are best for output that humans can read. For binary or huge outputs, compare a hash and keep the full file out of the test message.

Designing code that is easy to test

Table tests are only pleasant when the code under test can be called with plain values and returns plain values. The hard part of testing is usually not the test, it is the code that reaches out to the world: a database, the system clock, the network, the file system. The cure is the Go proverb accept interfaces, return structs (interface design goes deeper). Define a small interface in the package that uses the dependency, covering only the methods you call. In production you pass the real thing; in a test you pass a fake: a tiny hand-written type that records calls and returns canned answers. No mocking library is needed.

Go Fakes for a store and a clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The test needs no database and no waiting for noon: every row picks its own time of day. The "midnight counts as morning" row pins down a boundary that is easy to get wrong, and writing it down as a named case documents the decision for the next reader.

For time, the pattern is the same: pass a Clock interface, or even simpler, pass a now func() time.Time field that tests overwrite. For code that uses timers, tickers and time.Sleep, see testing/synctest in testing concurrent code, which gives you a fake clock without changing the code at all.

Don't define interfaces "for testing" everywhere. If a function only calls strings.ToUpper, there is nothing to fake. Add an interface where the code touches something slow, random or outside your process, and keep it to the methods you actually call.

Testing HTTP handlers with httptest

The net/http/httptest package lets you test handlers without opening a real port. httptest.NewRequest builds a request, httptest.NewRecorder is a ResponseWriter that remembers what was written, and you call the handler directly. That fits a table perfectly:

Go A table test for an HTTP handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The handler ran in the test goroutine with no network involved, so the test is fast and deterministic. Use httptest.NewServer instead when you need a real listener, for example to test an HTTP client (the HTTP client lesson does exactly that). Full handler and middleware testing continues in handlers and middleware.

What makes a good table

  • One behavior per row. If a row needs a comment to explain what it checks, split it or rename it.
  • Include the edges: empty input, one item, the boundary values, a very large value, Unicode, and every error return.
  • Keep the loop body boring. If the loop needs if tt.kind == ... branches, you have two tests glued together; write two tables.
  • Don't re-implement the function in the test. Computing want with the same algorithm proves nothing. Write the literal expected value.
  • Prefer got, want order in messages and always print the input: Slug("") = "x", want "" is a report you can act on.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line in a table test starts a named subtest that you can run on its own with -run?

    t.Run creates a subtest whose name is built from the parent test and the given name, so go test -run 'TestSlug/digits' can select just that case.
  2. 2. A subtest is named "extra spaces". What does it appear as in go test -v output?

    t.Run rewrites spaces in the subtest name to underscores so the name is easy to type in a -run pattern.
  3. 3. What does calling t.Helper() as the first statement of an assertion function change?

    t.Helper marks the function as a helper, so the testing package skips it when it chooses the file:line to print and reports the caller instead.
  4. 4. Why is the line tt := tt at the start of the loop body unnecessary in Go 1.22 and later?

    Go 1.22 gave every iteration of a for loop a fresh variable, so closures and parallel subtests no longer share one tt.
  5. 5. You want to test code that depends on a database. What is the idiomatic Go approach?

    Go favors small interfaces declared by the consumer; a fake that implements the two or three methods you call is simple and needs no framework.

Summary

  • A table-driven test is a slice of case structs plus one loop; t.Run gives each case a name so you can run and read it separately.
  • Since Go 1.22 you no longer need tt := tt; every iteration has its own variable.
  • Test errors with errors.Is/errors.As and a wantErr column, never by message text.
  • Mark helpers with t.Helper(), and use t.Cleanup, t.TempDir and t.Setenv instead of manual cleanup.
  • t.Parallel() runs independent subtests concurrently; combine it with -race and never with t.Setenv.
  • Golden files in testdata/ hold large expected outputs; regenerate them with an -update flag and review the diff.
  • Make code testable with small consumer-side interfaces and hand-written fakes for databases, clocks and clients; use httptest for handlers.

Next: Benchmarks and Fuzzing