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.
Code
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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Table Driven Tests With Subtests?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.