Idiomatic Testing in Go

Idiomatic Testing in Go in Go: An inspection bench in a workshop has a jig: a fixture that holds every part in exactly the same position so the identical…

The Analogy: One Jig, Many Parts

An inspection bench in a workshop has a jig: a fixture that holds every part in exactly the same position so the identical measurement can be taken over and over. The jig is built once. Parts arrive in a tray, each with a label. The inspector does not write a new procedure per part -- they drop the next part into the jig, take the measurement, and write down the label of anything that came out wrong.

Go's testing package is that bench and nothing more. There is no assertion library, no annotations, no test-runner DSL, no lifecycle framework. A test is a function named TestSomething taking a *testing.T, living in a file ending _test.go. You call your own code, compare the result to what you expected, and if they differ you call t.Errorf with a sentence describing the difference. That is the entire contract.

The jig, in practice, is a table: a slice of structs holding the inputs and the expected outputs, and one loop that measures each. Wrap the body in t.Run(tc.name, ...) and every row gets its own line in the report, its own pass or fail, and its own selector -- go test -run 'TestMake/only' runs one row. Adding a case becomes a one-line change, which is the difference between a suite people extend and a suite people avoid.

Where the analogy stops: the parts and the bench are made of the same material. Test files are ordinary Go compiled into the package, so a test in package config can reach every unexported identifier, while a test in package config_test -- legal in the same directory -- sees only the exported API and therefore consumes it exactly as a stranger would. The bench also has features a workshop does not: results are cached, t.Parallel opts a test into concurrency, t.TempDir and t.Cleanup handle teardown, Example functions double as compiled documentation, and go vet runs on the way through.


Syntax or Core Structure

// slug/slug.go
package slug

import "strings"

// Make turns a title into a URL slug: lower case, words joined by single
// hyphens, every other character treated as a separator and dropped.
func Make(s string) string {
	var b strings.Builder
	sep := false
	for _, r := range strings.ToLower(s) {
		switch {
		case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
			if sep && b.Len() > 0 {
				b.WriteByte('-')
			}
			sep = false
			b.WriteRune(r)
		default:
			sep = true
		}
	}
	return b.String()
}
// slug/slug_test.go
package slug

import "testing"

func TestMake(t *testing.T) {
	tests := []struct {
		name string
		in   string
		want string
	}{
		{"simple", "Hello, World!", "hello-world"},
		{"digits", "  Go 1.22  ", "go-1-22"},
		{"empty", "", ""},
		{"only separators", "---", ""},
		{"ampersand", "Ada&Grace", "ada-grace"},
		{"trailing dash", "Go!", "go-"}, // deliberately wrong, see the output
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			got := Make(tc.in)
			if got != tc.want {
				t.Errorf("Make(%q) = %q, want %q", tc.in, got, tc.want)
			}
		})
	}
}
go test ./slug/

Output:

--- FAIL: TestMake (0.00s)
    --- FAIL: TestMake/trailing_dash (0.00s)
        slug_test.go:24: Make("Go!") = "go", want "go-"
FAIL
FAIL    example.com/myapp/slug  0.004s
FAIL

Four details are doing real work here. Without -v, go test prints only failures, but it prints the whole path -- parent, subtest, and the exact file and line -- so a CI log tells you which row broke without you running anything locally. The subtest name only separators became only_separators because spaces are escaped in the test path. The failure message names the input, the result and the expectation in that order, so nobody has to open the file to understand it. And the expectation was the thing that was wrong: Make("Go!") really is "go", because a separator is only ever written before the next kept rune, which is precisely how trailing hyphens are avoided. Elapsed figures vary between runs; nothing else in that block does.


Technical Depth: Everything the Toolchain Knows About

The five signatures

SignaturePurpose
func TestXxx(t *testing.T)A test
func BenchmarkXxx(b *testing.B)A benchmark, covered in Module 11
func FuzzXxx(f *testing.F)Coverage-guided fuzzing, since Go 1.18
func ExampleXxx()Compiled documentation; verified if it has an // Output: comment
func TestMain(m *testing.M)Wraps the whole binary; must call m.Run() and os.Exit with its code

The name is matched strictly: the prefix must be followed by a rune that is not lower case, so TestMake and Test_make are found and Testmake is silently ignored -- a bug that has hidden entire files of tests.

White box and black box in one directory

A directory may contain two package names: config and config_test. Files in package config see the unexported world; files in package config_test must import the package and see only its exported surface. Prefer the second, because a test that only touches the API cannot be broken by a refactor that keeps behaviour intact, and it doubles as proof that the API is usable. Keep a white-box file for the handful of internals that genuinely need direct exercise.

Error, Fatal, and where you are allowed to call them

t.Errorf marks the test failed and carries on, which is what you want when several independent facts are worth reporting from one run. t.Fatalf marks it failed and calls runtime.Goexit, which is why it must be called from the test's own goroutine -- a t.Fatal inside a goroutine you spawned kills that goroutine and lets the test pass. Send the failure back through a channel, or use t.Errorf, which is goroutine-safe.

Inside a table loop, this interacts with t.Run: a Fatalf in a subtest ends only that subtest, whereas the same call in a bare loop ends the entire test and you never learn about rows 4 through 12.

The helpers that replace a lifecycle framework

CallBehaviour
t.Helper()Marks the function as a helper so reported line numbers point at the caller
t.Cleanup(fn)Runs fn when the test and its subtests finish, LIFO, even after Fatal
t.TempDir()A unique directory, deleted automatically; safe under t.Parallel
t.Setenv(k, v)Sets and restores an env var; panics if the test is parallel
t.Skip, testing.Short()Opt out, typically guarded by -short
t.Context()A context cancelled just before cleanup, since Go 1.24

Parallelism and the loop variable

t.Parallel() signals that a subtest may run alongside its siblings: it pauses, the parent returns, then all paused subtests resume together. The classic bug is capturing the range variable -- before Go 1.22 every parallel subtest saw the final row, and the fix was the tc := tc line still visible in older code. Go 1.22 made loop variables per-iteration, but only for modules whose go.mod declares go 1.22 or later, so on an older directive the shadow line is still required.

Flags worth knowing

FlagEffect
-run 'TestMake/only'Regexp matched per path element, so it selects one subtest
-vStreams === RUN lines and lists passing subtests too
-count=1Defeats the result cache; (cached) in the output means nothing ran
-raceEnables the race detector; roughly 5x slower and worth every cycle
-cover, -coverprofile=c.outStatement coverage, viewable via go tool cover -html=c.out
-timeout 30sPanics with all stacks after the limit; the default is 10 minutes
-shuffle=onRandomises test order to expose inter-test dependencies

Caching is keyed on the test binary and the files and environment it touched, which is why an unchanged package prints (cached) instantly. It is a feature, not a stale result -- but a test that reads the network or the clock can be cached wrongly, which is a reason to keep tests hermetic.

Comparing results

Use == for comparable types, including structs of comparable fields. For slices and maps prefer slices.Equal and maps.Equal (Go 1.21) over reflect.DeepEqual: they are typed, faster, and will not silently succeed on two nil-versus-empty values you meant to distinguish. For errors use errors.Is or errors.As, never a string comparison on err.Error(). For floats compare against a tolerance.


Real World Example: A Config Loader, Tested From the Outside

Seven behaviours, two error taxonomies, and a filesystem -- covered by one table, one fixture helper, and no third-party dependencies.

// config/config.go
package config

import (
	"errors"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var (
	ErrMissing = errors.New("missing key")
	ErrSyntax  = errors.New("bad syntax")
	ErrRange   = errors.New("out of range")
)

type Config struct {
	Name    string
	Workers int
}

func Load(path string) (Config, error) {
	b, err := os.ReadFile(path)
	if err != nil {
		return Config{}, fmt.Errorf("load config: %w", err)
	}
	return Parse(string(b))
}

func Parse(text string) (Config, error) {
	kv := map[string]string{}
	for _, line := range strings.Split(text, "\n") {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		k, v, ok := strings.Cut(line, "=")
		if !ok {
			return Config{}, fmt.Errorf("parse %q: %w", line, ErrSyntax)
		}
		kv[strings.TrimSpace(k)] = strings.TrimSpace(v)
	}

	c := Config{Name: kv["name"], Workers: 1}
	if c.Name == "" {
		return Config{}, fmt.Errorf("key name: %w", ErrMissing)
	}
	if s, ok := kv["workers"]; ok {
		n, err := strconv.Atoi(s)
		if err != nil {
			return Config{}, fmt.Errorf("key workers: %w", err)
		}
		if n < 1 || n > 64 {
			return Config{}, fmt.Errorf("key workers = %d: %w", n, ErrRange)
		}
		c.Workers = n
	}
	return c, nil
}
// config/config_test.go
package config_test // black box: only the exported API is visible

import (
	"errors"
	"os"
	"path/filepath"
	"strconv"
	"testing"

	"example.com/myapp/config"
)

// write builds a fixture file. t.Helper() makes any failure inside it report
// the caller's line, and t.TempDir() cleans up without a defer.
func write(t *testing.T, body string) string {
	t.Helper()
	path := filepath.Join(t.TempDir(), "app.conf")
	if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
		t.Fatalf("write fixture: %v", err)
	}
	return path
}

func TestParse(t *testing.T) {
	tests := []struct {
		name    string
		body    string
		want    config.Config
		wantErr error // nil means "expect success"
	}{
		{"defaults", "name = api\n",
			config.Config{Name: "api", Workers: 1}, nil},
		{"explicit workers", "name=api\nworkers = 8\n",
			config.Config{Name: "api", Workers: 8}, nil},
		{"comments and blanks", "# app\n\nname=api\n",
			config.Config{Name: "api", Workers: 1}, nil},
		{"no name", "workers=2\n", config.Config{}, config.ErrMissing},
		{"bad line", "name=api\nnonsense\n", config.Config{}, config.ErrSyntax},
		{"too many workers", "name=api\nworkers=999\n", config.Config{}, config.ErrRange},
		{"workers not a number", "name=api\nworkers=eight\n", config.Config{}, strconv.ErrSyntax},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			got, err := config.Parse(tc.body)
			// errors.Is(err, nil) is true exactly when err is nil, so one
			// comparison covers both the success and failure rows.
			if !errors.Is(err, tc.wantErr) {
				t.Fatalf("Parse() error = %v, want %v", err, tc.wantErr)
			}
			if err == nil && got != tc.want {
				t.Errorf("Parse(%q) = %+v, want %+v", tc.body, got, tc.want)
			}
		})
	}
}

func TestLoad(t *testing.T) {
	t.Run("from file", func(t *testing.T) {
		got, err := config.Load(write(t, "name=api\nworkers=4\n"))
		if err != nil {
			t.Fatalf("Load() error = %v", err)
		}
		want := config.Config{Name: "api", Workers: 4}
		if got != want {
			t.Errorf("Load() = %+v, want %+v", got, want)
		}
	})

	t.Run("missing file", func(t *testing.T) {
		_, err := config.Load(filepath.Join(t.TempDir(), "nope.conf"))
		if !errors.Is(err, os.ErrNotExist) {
			t.Fatalf("Load() error = %v, want os.ErrNotExist", err)
		}
	})
}
go test -v ./config/

Output:

=== RUN   TestParse
=== RUN   TestParse/defaults
=== RUN   TestParse/explicit_workers
=== RUN   TestParse/comments_and_blanks
=== RUN   TestParse/no_name
=== RUN   TestParse/bad_line
=== RUN   TestParse/too_many_workers
=== RUN   TestParse/workers_not_a_number
--- PASS: TestParse (0.00s)
    --- PASS: TestParse/defaults (0.00s)
    --- PASS: TestParse/explicit_workers (0.00s)
    --- PASS: TestParse/comments_and_blanks (0.00s)
    --- PASS: TestParse/no_name (0.00s)
    --- PASS: TestParse/bad_line (0.00s)
    --- PASS: TestParse/too_many_workers (0.00s)
    --- PASS: TestParse/workers_not_a_number (0.00s)
=== RUN   TestLoad
=== RUN   TestLoad/from_file
=== RUN   TestLoad/missing_file
--- PASS: TestLoad (0.00s)
    --- PASS: TestLoad/from_file (0.00s)
    --- PASS: TestLoad/missing_file (0.00s)
PASS
ok      example.com/myapp/config        0.006s

Nine behaviours are covered by about fifteen lines of measurement code, and the wantErr column is why. Because errors.Is(err, nil) is true exactly when err is nil, the success rows and the failure rows go through the same comparison -- no if tc.wantErr == nil { ... } else { ... } split, no duplicated structure, and adding a tenth behaviour is one line in the table. The second check is guarded by err == nil because a returned zero Config on the error path is not something worth asserting.

The test file declares package config_test, so it can only reach Config, Parse, Load and the three sentinels -- exactly what a real caller gets. That constraint is the point: no test here can be broken by renaming the kv map or restructuring the loop, and the suite is standing proof that the API is usable without inside knowledge. If some internal needed direct exercise, the answer is a second file declaring package config in the same directory, not the export of a field.

write is what a setup framework would have been. t.Helper() means that if os.WriteFile fails, the reported line is the write(t, ...) call in the subtest rather than a line inside the helper, so the report names the row that broke. t.Fatalf is right there because a broken fixture is not a finding about Load -- there is nothing to learn from continuing. And t.TempDir() gives each subtest a private directory that is deleted automatically, which is what makes these tests hermetic enough to be cached, shuffled, or run in parallel without changes.

One row deserves suspicion rather than praise. Asserting strconv.ErrSyntax works -- *strconv.NumError implements Unwrap, so the sentinel survives Parse's %w -- but it couples the test to the fact that Parse happens to use strconv.Atoi. Swap in a hand-rolled parser and a passing test breaks with no behaviour change. The honest fix belongs in Parse, not the test: map the conversion failure to ErrSyntax so the package's own vocabulary is the whole contract. Note finally what is absent from all of this -- no assertion library, no mocks, no lifecycle hooks -- and that go test quietly ran a subset of go vet first, which is why every config.Config literal here names its fields.


Common Mistakes

  1. Failure messages with no evidence. t.Error("failed") or t.Error("mismatch") forces the reader to open the file and reconstruct the case. Print the input, the result and the expectation: Make(%q) = %q, want %q.
  2. A bare table loop with no t.Run. One Fatalf ends the whole test, the report names no row, and -run cannot select a single case. Subtests cost one line.
  3. t.Fatal from a spawned goroutine. It calls runtime.Goexit, killing that goroutine only, so the test finishes green with a failure you never saw. Report through a channel, or use t.Errorf.
  4. Capturing the range variable in a parallel subtest. On a go.mod declaring less than go 1.22, every parallel row sees the last case. Either raise the directive or keep the tc := tc line.
  5. t.Setenv in a parallel test. It panics, deliberately: environment is process-wide and cannot be scoped to one of several concurrent tests.
  6. String-matching errors. if err.Error() != "missing key" breaks the moment a layer adds context, which is exactly what good wrapping does. Use errors.Is or errors.As.
  7. reflect.DeepEqual as a default. It is slow, untyped, treats nil and empty slices as different, and compares errors by structure rather than identity. Prefer ==, slices.Equal, maps.Equal, errors.Is.
  8. Testing unexported internals. Asserting on a private field or helper means every refactor breaks a test while behaviour is unchanged. Test at the package boundary.
  9. Depending on map iteration order. Go randomises it on purpose, so a test that compares unsorted map-derived output passes most of the time and fails in CI. Sort first.
  10. time.Sleep as synchronisation. It is slow when it works and flaky when it does not. Wait on a channel or a sync.WaitGroup, and inject a clock rather than sleeping for one.
  11. Skipping -race, chasing 100% coverage. The first hides real bugs in any concurrent code; the second produces tests written to touch lines rather than to check behaviour. Coverage is a hint about what you forgot, not a target.

Best Practices

  • Write table-driven tests with t.Run and human-readable case names, so the report reads like a specification of the behaviour.
  • Put the input, the result and the expectation in every failure message, in got, want order, and name the function that produced them.
  • Assert errors with errors.Is and errors.As against sentinels your own package owns, so the test documents the contract rather than the implementation.
  • Default to package foo_test and keep a separate white-box file for the few internals that genuinely need it.
  • Call t.Helper() in every fixture function, and prefer t.Cleanup and t.TempDir to defer inside helpers, since they also run after Fatal and cover subtests.
  • Keep the test binary hermetic: no network, no wall clock, no assumptions about the working directory. Hermetic tests are cacheable, shufflable and parallelisable for free.
  • Run -race in CI, add -shuffle=on to catch tests that depend on each other, and use -count=1 when you deliberately want to bypass the cache.
  • Write Example functions with // Output: comments for the API's happy path -- they appear in the documentation and fail the build when they drift.

Practice Exercises

  1. Convert to a table. Take three repetitive TestAddOne, TestAddTwo, TestAddNegative functions and fold them into one table-driven test with t.Run. Then run a single case with -run and paste the command you used.
  2. Test both taxonomies. Write Split(s, sep string) ([]string, error) returning ErrEmptySep for an empty separator, and cover it with a table whose wantErr column is compared using errors.Is and whose want slice is compared using slices.Equal.
  3. Build a fixture helper. Write newStore(t *testing.T) *Store that uses t.TempDir and t.Cleanup, calls t.Helper, and t.Fatalfs on setup failure. Use it from three subtests and confirm a deliberately broken fixture reports the caller's line.
  4. Break a parallel test on purpose. Write five parallel subtests that each capture the loop variable, set go 1.21 in go.mod, and record which case name every row reports. Raise the directive to go 1.22 and record the difference.