Use table-driven tests and subtests
Use table-driven tests and subtests
A table-driven test stores inputs and expected results as records, then runs the same assertion for each record. Give each case a descriptive name. t.Run creates a subtest, whose name and result appear separately; it can also be selected using go test -run. These examples execute sequentially.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- calc.go ---package calc
func Abs(n int) int { if n < 0 { return -n } return n}
--- calc_test.go ---package calc
import "testing"
func TestAbs(t *testing.T) { cases := []struct { name string in, want int }{{"negative", -4, 4}, {"zero", 0, 0}, {"positive", 3, 3}} for _, c := range cases { t.Run(c.name, func(t *testing.T) { if got := Abs(c.in); got != c.want { t.Errorf("got %d want %d", got, c.want) } }) }}Each row is independent. The case name identifies the failing input. This simple Abs implementation is for small integers; the minimum representable int cannot be negated without overflow. Add a stated range contract before using it generally.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestAbs/negativeCheck an error condition in the table
--- go.mod ---module example.test/lesson
go 1.23
--- calc.go ---package calc
func Divide(a, b int) (int, bool) { if b == 0 { return 0, false } return a / b, true}
--- calc_test.go ---package calc
import "testing"
func TestDivide(t *testing.T) { for _, c := range []struct { name string a, b, want int ok bool }{{"valid", 8, 2, 4, true}, {"zero", 8, 0, 0, false}} { t.Run(c.name, func(t *testing.T) { got, ok := Divide(c.a, c.b) if got != c.want || ok != c.ok { t.Errorf("got %d,%t want %d,%t", got, ok, c.want, c.ok) } }) }}The expected boolean is part of the contract. Run go test -run "^TestDivide$/^zero$" -v to select the zero subtest and its parent. The loop callback runs synchronously here; parallel subtests require attention to loop-variable language version and shared mutable state.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestDivide/zeroTry it locally
Write a table-driven test for IsEven with named cases 0, 3 and -4. Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Testing fundamentals 02: Use table-driven tests and subtests
Check the lesson objective before moving on.
What does t.Run provide?
Why store expected results separately?