Subtests
t.Run(name, func(t *testing.T)) starts a nested test. Failures are scoped to the name. -run TestParse/empty runs one child. Subtests can call t.Parallel independently.
Detailed Explanation
A table loop without t.Run stops at the first t.Fatal and reports one failure. With t.Run, each case is a child: the parent continues to the next Run, and the output is TestParse/empty. That is the whole feature, plus parallel.
Names. Use a stable, file-safe name: letters, digits, underscores. Spaces become underscores in -run. Slash starts a new level: t.Run("a", ...) plus inner t.Run("b") is -run TestX/a/b.
Parallel. t.Parallel() in a subtest lets that child run alongside other parallel tests. The parent waits for its children before returning. Shared fixtures must not be mutated. t.Cleanup on the parent runs after children finish.
Setup/teardown. Put shared setup in the parent, then t.Run. Put per-case setup in the child. t.Cleanup on the child runs when that child ends.
What it costs. A subtest is a function call and a name in the runner. Thousands of subtests are fine. Deep nesting (five levels) is usually a sign the package under test is doing too much in one API.
Code Examples
package parse
import "testing"
func TestParse(t *testing.T) {
t.Run("ok", func(t *testing.T) {
if _, err := parsePort("8080"); err != nil {
t.Fatal(err)
}
})
t.Run("empty", func(t *testing.T) {
if _, err := parsePort(""); err == nil {
t.Fatal("expected error")
}
})
}
func parsePort(s string) (int, error) {
if s == "" {
return 0, errBad
}
return 8080, nil
}
var errBad = errString("bad")
type errString string
func (e errString) Error() string { return string(e) }func TestParallel(t *testing.T) {
for _, n := range []int{1, 2, 3} {
n := n
t.Run(fmt.Sprintf("%d", n), func(t *testing.T) {
t.Parallel()
_ = n
})
}
}Common Gotchas
`t.Fatal` in the parent before `t.Run` skips children
fail after, or use `t.Error`.
The parent is not `Parallel` just because children are
call `t.Parallel` on the parent too if the whole group should overlap other tests.