Table Driven Tests With Subtests

Enumerate cases in a table and run each as a subtest with t.Run, so one failure names the case instead of failing the suite.

GoData Integrity

Code

gosnippet
39 lines
package main

import (
	"fmt"
	"strings"
	"testing"
)

func slugify(s string) string {
	s = strings.ToLower(strings.TrimSpace(s))
	return strings.ReplaceAll(s, " ", "-")
}

func TestSlugify(t *testing.T) {
	cases := []struct {
		name string
		in   string
		want string
	}{
		{"simple", "Hello World", "hello-world"},
		{"trims edges", "  padded  ", "padded"},
		{"single word", "Solo", "solo"},
	}

	for _, tc := range cases {
		tc := tc
		// t.Run:每个用例独立子测试,失败信息带用例名
		t.Run(tc.name, func(t *testing.T) {
			if got := slugify(tc.in); got != tc.want {
				t.Fatalf("slugify(%q) = %q, want %q", tc.in, got, tc.want)
			}
		})
	}
}

func main() {
	// 演示输出(测试本身用 go test 运行)
	fmt.Println(slugify("Hello World"))
}

How the file gets its output

Count the functions slugify, TestSlugify and main as the entire surface area of Table Driven Tests With Subtests.

The cycling part of this snippet is for _, tc := range cases.

Applying it

Entry signature: func TestSlugify(t *testing.T)

The entry point wires slugify together — run it once and the whole demo flows.

Statements that matter

func slugify(s string) string {
s = strings.ToLower(strings.TrimSpace(s))
return strings.ReplaceAll(s, " ", "-")
}
for _, tc := range cases {
tc := tc
// t.Run:每个用例独立子测试,失败信息带用例名
t.Run(tc.name, func(t *testing.T) {
if got := slugify(tc.in); got != tc.want {
t.Fatalf("slugify(%q) = %q, want %q", tc.in, got, tc.want)
}
})
}
func main() {
// 演示输出(测试本身用 go test 运行)
fmt.Println(slugify("Hello World"))
}

Interactive Tools for This Topic

FAQ

How do you run Table Driven Tests With Subtests?
It runs as-is — treat the file as the whole program and execute it.