Skip to content
Tutorials Center
My learning

Topics

Lesson 99 of 147 ยท Testing and Tooling

Testing with the testing Package

Write Go tests with the testing package - _test.go files, t.Error and t.Fatal, helpers, cleanup, TempDir, subtests with t.Run and how to run them with go test.

Go ships with a testing framework in its standard library. There is no separate test runner to install, no assertion library you must choose, and no special syntax: a test is an ordinary function in an ordinary file, run by the go test command. That simplicity is deliberate. Because tests are plain Go, you already know how to write them: call your code, compare the result with what you expect, and report a failure if they differ.

This lesson shows how that works. You will learn the naming rules for test files and functions, how to report failures with t.Error and t.Fatal, how to factor out helpers and cleanup, how subtests with t.Run organize cases, how to run and filter tests with go test, and how external test packages and TestMain fit in. The next lesson, Table-Driven Tests and Testable Design, builds on this to write tests that scale.

The browser editors here cannot run go test, which needs a module on disk. So test files and go test output appear as read-only blocks marked as what you would see on your machine. The runnable examples use two honest alternatives: a small test runner written by hand to show what testing does, and testing.Main, the function that a generated test binary uses, to run real testing.T tests inside an ordinary program.

Your first test

Suppose reverse.go contains a function:

Go
// file: strutil/reverse.go
package strutil

// Reverse returns s with its runes 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)
}

Its test lives next to it, in a file whose name ends in _test.go:

Go
// file: strutil/reverse_test.go
package strutil

import "testing"

func TestReverse(t *testing.T) {
	got := Reverse("hรฉllo")
	want := "ollรฉh"
	if got != want {
		t.Errorf("Reverse(%q) = %q, want %q", "hรฉllo", got, want)
	}
}

Running go test in that directory compiles the package together with its test files, runs every test, and prints a verdict:

TEXT
$ go test
PASS
ok  	example.com/strutil	0.002s

Four rules make a test function recognizable:

  1. It lives in a file named *_test.go. Those files are compiled only by go test, never into your program.
  2. Its name starts with Test followed by a name that begins with an uppercase letter or digit (TestReverse, Test2D). Testreverse is not a test.
  3. It takes exactly one parameter, t *testing.T, and returns nothing.
  4. It is in the same package as the code (a "white-box" test that can use unexported names), or in the package name with the suffix _test (a "black-box" test, below).

A test passes if it returns without recording a failure, and fails if it calls t.Error, t.Fatal or their variants, or panics. There is no assert keyword and no exception to catch.

Reporting failures: Error versus Fatal

The *testing.T value is your handle for reporting. These are the methods you will use constantly:

Method Effect
t.Log, t.Logf Print a message, shown only for failing tests or with -v
t.Error, t.Errorf Mark the test as failed and continue running it
t.Fatal, t.Fatalf Mark the test as failed and stop it immediately
t.Fail, t.FailNow Mark as failed without a message (continuing / stopping)
t.Skip, t.Skipf Stop the test and mark it skipped
t.Helper Mark the calling function as a test helper (cleaner line numbers)
t.Cleanup Register a function to run when the test ends
t.TempDir Create a temporary directory deleted afterwards
t.Setenv Set an environment variable for this test only
t.Run Run a named subtest

Use Errorf when later checks are still meaningful, so one run shows every problem, and Fatalf when continuing would be pointless or would panic (for instance, if the value you are about to dereference is nil). The convention for messages is "got, want": say what the function was called with, what it returned and what you expected, in that order. A good message makes a failure understandable without opening the code.

To see these rules in action without a module, here is a miniature version of testing, written by hand: a T type with Errorf and Fatalf, and a run function that executes a test, recovers from panics and prints a verdict. The test cases are deliberately flawed.

Go A hand-made test runner (some tests fail 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.

Read the output closely, because it is the whole idea of a test framework in forty lines:

  • Two tests pass. TestTitleUnicode fails with a real bug that the test found: s[:1] cuts a byte, not a character, so the two-byte letter รฉ is split and the result is not even valid UTF-8 (the report prints it as "๏ฟฝ\xa9lan"). A fix would use []rune as in the Strings, Bytes and Runes lesson. Notice that the second Errorf also printed: after a plain error the test keeps going.
  • TestPanics crashes with a nil-map write. The runner recovered from the panic and reported it as a failure, so the other tests still ran. The real package does the same: a panicking test marks that test as failed and stops it. (In the real framework a panic in a test aborts the whole test binary after reporting, so panics are worse than failed assertions.)
  • TestFatal stops at Fatalf: the line after it never runs. In the real package Fatal calls runtime.Goexit to end the test goroutine, which is why you must call it from the goroutine running the test, never from one the test starts.

Running real tests

testing.Main is the function a generated test binary calls. It accepts a list of tests, runs them and prints the same report as go test -v. We use it with ordinary testing.T code. This program has a generic stack, two helper functions and tests that use t.Helper, t.Cleanup, t.TempDir, t.Setenv and t.Skip:

Go Real testing.T tests with helpers, cleanup and skipping

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.

(testing.Init() registers the -test.* flags, and flag.Set("test.v", "true") turns on the verbose output that go test -v would give. You never write this boilerplate in a real project; go test generates it for you.)

Several features are visible in that output:

  • t.Log lines carry a line number (main.go:45), the place where the message was written. The cleanup message reports line 27 because t.Log was called there, inside the function passed to t.Cleanup.
  • Cleanup runs after the test finishes, in last-in-first-out order, even if the test failed or called t.Fatal. It is the testing counterpart to defer, but works across helper functions: newStack registered the cleanup, and TestStackOrder benefited without knowing. Use it to close files, stop servers and restore global state.
  • t.Helper() tells the framework that newStack and assertPop are not the interesting place to point at. If assertPop fails, the failure message shows the line in TestStackOrder that called it. Call it first in every test helper.
  • t.TempDir() gives each test its own empty directory and deletes it automatically. t.Setenv restores the environment variable afterwards (so it cannot be combined with t.Parallel).
  • t.Skip ends a test and prints it as skipped. Typical uses are tests that need a database or network, platform-specific tests, and slow tests when testing.Short() is true (go test -short).

What a failure looks like

Here is what a test report looks like when assertions fail. Errorf and Log do not stop the test; Fatalf does, and the next test still runs:

Go A failing test and its report (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 program ends with FAIL and a non-zero exit code, which is what makes go test usable in CI: the exit status tells the pipeline whether to continue. The first message shows a real mistake in the test itself (the test calls Abs(-4) but its message says -3). Always compute the message from the same values you tested, so the report cannot lie. Three messages were recorded for TestAbs, each with the line number where it was reported, and TestAfter still ran and passed.

Subtests with t.Run

t.Run(name, func(t *testing.T) { ... }) runs a subtest: a test inside a test, with its own name, its own pass/fail result, and its own t. Subtests let you:

  • group related checks under a descriptive name (TestSlug/empty),
  • run one case alone with -run,
  • get a separate verdict per case instead of "something failed",
  • share expensive setup in the parent while each case stays isolated.

They are the building block of table-driven tests, the topic of the next lesson. Their names make filtering possible. Here, -test.run is set to a regular expression with a slash: the part before the slash selects top-level tests, the part after selects subtests (spaces in names become underscores).

Go Filtering subtests the way go test -run does

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.

Only TestSlug/simple and TestSlug/empty ran; spaces, already and TestOther were skipped by the filter. In a real project you would run exactly that with go test -run 'TestSlug/(simple|empty)' -v. Note that the loop variable tc is captured by each subtest's closure: since Go 1.22, every iteration gets its own copy, so this is safe, even for parallel subtests. In older code you will see tc := tc inserted as a workaround.

Running tests with go test

Everything you can do from the command line, as you would see it on your own machine:

Terminal
go test                      # the package in the current directory
go test ./...                # every package in the module
go test -v                   # verbose: show each test and its logs
go test -run TestReverse     # only tests whose name matches this regular expression
go test -run 'TestSlug/empty' -v
go test -count=1 ./...       # ignore cached results and run again
go test -short ./...         # tests can check testing.Short() and skip slow work
go test -failfast ./...      # stop after the first failure
go test -shuffle=on ./...    # randomize test order to expose hidden dependencies
go test -timeout 30s ./...   # fail if the run takes longer (default is 10 minutes)
go test -cover ./...         # print statement coverage
go test -coverprofile=c.out ./... && go tool cover -html=c.out
go test -race ./...          # enable the data race detector

Typical output for a module with two packages:

TEXT
$ go test ./...
ok  	example.com/strutil	0.003s
FAIL	example.com/cart	0.004s
FAIL

$ go test -v -run 'TestSlug/(simple|empty)' ./strutil
=== RUN   TestSlug
=== RUN   TestSlug/simple
=== RUN   TestSlug/empty
--- PASS: TestSlug (0.00s)
    --- PASS: TestSlug/simple (0.00s)
    --- PASS: TestSlug/empty (0.00s)
PASS
ok  	example.com/strutil	0.002s

$ go test -cover ./strutil
ok  	example.com/strutil	0.002s	coverage: 85.7% of statements

A few facts that save time:

  • Results are cached. If neither the code nor the test inputs changed, go test prints (cached) and reruns nothing. Use -count=1 to force a run, for instance when a test depends on the outside world.
  • go test applies a small go vet check automatically before running, so serious mistakes (like a wrong Printf verb in t.Errorf) fail the build.
  • Directories named testdata are ignored by the go tool, so they are the right place for fixtures such as sample input files. Tests run with their package directory as the working directory, which makes os.ReadFile("testdata/input.json") work.
  • The coverage percentage tells you which statements ran, not whether the assertions are good. Use it to find untested code, not as a target to maximize.

Black-box tests and TestMain

A test file normally declares the same package as the code, so it can reach unexported names. If you want a test to see only what users of the package see, use an external test package with the suffix _test in the same directory:

Go
// file: strutil/reverse_external_test.go
package strutil_test

import (
	"testing"

	"example.com/strutil"
)

func TestReverseAPI(t *testing.T) {
	if got := strutil.Reverse("ab"); got != "ba" {
		t.Errorf("got %q", got)
	}
}

Both kinds can live side by side. Black-box tests make sure the exported API is usable and are the right choice for examples and for avoiding import cycles (a package that your package imports may need to test against yours). White-box tests are better for tricky internals. Use both without guilt.

Sometimes a package needs setup that must run exactly once around all its tests: start a database container, set a global, parse flags. Define TestMain:

Go
func TestMain(m *testing.M) {
	// before any test runs
	setupDatabase()

	code := m.Run() // run all tests

	// after all tests
	teardownDatabase()
	os.Exit(code)
}

If a package has a TestMain, the framework calls it instead of running the tests directly, and your code decides when (and whether) to call m.Run. Keep it rare: it is global state, and t.Cleanup with helper functions handles most needs more locally.

Practical advice

  • Test behavior, not implementation. Call the public functions with realistic inputs and check results; tests that mirror the code line by line break on every refactor.
  • Keep tests independent. No test should rely on another one having run. Use -shuffle=on occasionally to catch hidden coupling.
  • Write the failure message first. If a failure would read "got false, want true", improve the message until a stranger could diagnose it.
  • Don't import an assertion library by default. An if got != want { t.Errorf(...) } is clear, needs no dependency, and gives exact control over the message. Libraries such as testify are popular and fine, but they are a choice, not a requirement. For comparing complex values, reflect.DeepEqual or the slices.Equal/maps.Equal functions often do the job, and github.com/google/go-cmp/cmp produces readable diffs.
  • Test the error paths. Check that invalid input produces the right error, using errors.Is or errors.As (Wrapping and Inspecting Errors).
  • Recent additions. Go 1.24 added t.Context() (a context cancelled just before cleanup functions run), t.Chdir() for tests that need a working directory, and b.Loop() for benchmarks, which the benchmarks lesson covers.

The testing package also supports measurement. testing.AllocsPerRun counts allocations and testing.Benchmark runs a benchmark function programmatically. Both work in an ordinary main, so you can compare two implementations right here (the lesson reports only what is stable, not timings):

Go Measuring allocations and running a benchmark in main

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 naive version allocates a new string on every +=, so it makes roughly one allocation per part; the builder grows one buffer and allocates only a few times in total. We print comparisons, not numbers, because exact counts and times depend on the machine and the Go version. In a real benchmark you would look at ns/op and allocs/op in the go test -bench output. Benchmarks and Fuzzing shows how, and Table-Driven Tests and Testable Design is the natural next step.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which function is run by go test?

    A test function must start with Test followed by an uppercase letter or digit, and take exactly one *testing.T parameter. The other versions have a lowercase letter after Test, a lowercase first letter, or a non-pointer parameter.
  2. 2. What is the difference between t.Errorf and t.Fatalf?

    Both record a failure, but Fatalf ends the current test with runtime.Goexit. Other tests still run.
  3. 3. What does calling t.Helper() inside a helper function change?

    t.Helper marks the function as a helper so that the file and line in a failure message point at the caller, not inside the helper.
  4. 4. You want to run only the subtest empty of TestSlug. Which command does it?

    -run takes a regular expression, and a slash separates the pattern for the test from the pattern for its subtests.
  5. 5. Where should a test put sample input files?

    The go tool ignores directories named testdata, and tests run in their package directory, so relative paths like testdata/input.json work.

Summary

  • Tests are ordinary functions func TestXxx(t *testing.T) in _test.go files, run by go test; no extra framework is required.
  • t.Errorf records a failure and continues, t.Fatalf stops the test; write messages as "got, want" with the inputs.
  • t.Helper, t.Cleanup, t.TempDir, t.Setenv and t.Skip keep tests tidy; cleanup runs even when a test fails.
  • t.Run creates named subtests that can be filtered with -run 'Parent/child'; loop variables are per-iteration since Go 1.22.
  • Useful go test flags: -v, -run, -count=1, -short, -failfast, -shuffle=on, -cover, -race and -timeout. Results are cached.
  • Use package x_test for black-box tests, testdata/ for fixtures and TestMain only for once-per-package setup.
  • testing.Main, AllocsPerRun and Benchmark also work in an ordinary program, which is how this lesson ran real tests in the browser.

Next: Table-Driven Tests and Testable Design