Go core
Browse topics

Table-driven tests with subtests

Version
1.27
Since
1.7
Review
Draft

Summary#

A table-driven test lists inputs and expected results as data, then checks each row with the same code. t.Run turns each row into a named subtest that can fail and be selected on its own.

Syntax#

go
for _, tc := range cases {
	t.Run(tc.name, func(t *testing.T) {
		// Check one row.
	})
}

Example#

go
package mathutil

import "testing"

func abs(n int) int {
	if n < 0 {
		return -n
	}
	return n
}

func TestAbs(t *testing.T) {
	cases := []struct {
		name     string
		in, want int
	}{
		{name: "negative", in: -4, want: 4},
		{name: "zero", in: 0, want: 0},
		{name: "positive", in: 7, want: 7},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			if got := abs(tc.in); got != tc.want {
				t.Errorf("abs(%d) = %d, want %d", tc.in, got, tc.want)
			}
		})
	}
}

Expected output#

Save the example as abs_test.go in a temporary directory. Run this command there. It shows the test names and results while omitting elapsed times and the package summary.

sh
(
    output=$(go test -count=1 -v abs_test.go) || {
        printf '%s\n' "$output" >&2
        exit 1
    }
    printf '%s\n' "$output" |
        sed -nE 's/ \([0-9]+\.[0-9]+s\)$//; /^=== RUN|^[[:space:]]*--- PASS:|^PASS$/p'
)
Text
=== RUN   TestAbs
=== RUN   TestAbs/negative
=== RUN   TestAbs/zero
=== RUN   TestAbs/positive
--- PASS: TestAbs
    --- PASS: TestAbs/negative
    --- PASS: TestAbs/zero
    --- PASS: TestAbs/positive
PASS

Use go test -run 'TestAbs/zero' -v abs_test.go to select one row while developing.

Common mistakes#

Calling t.Fatalf directly in a loop without t.Run stops the remaining rows. Inside a subtest, report through the subtest's own t, the parameter of the function literal. Give rows distinct names so a failure points to one case.

Version applicability#

The example requires Go 1.7 for t.Run. In modules declaring Go 1.22 or later, for _, tc := range cases creates a fresh variable each iteration. With the older loop rules, copy tc inside the loop before using it in a parallel subtest.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0