snippetgoModeratepending
Go table-driven tests -- idiomatic test pattern
Viewed 0 times
table-driven testst.Runsubtesttest casestesting.T
go
Problem
Writing separate test functions for each case creates duplication. Adding new test cases requires copying boilerplate.
Solution
Use table-driven tests: define test cases as a slice of structs, iterate and run each as a subtest with t.Run.
Code Snippets
Table-driven tests with subtests
func TestSlugify(t *testing.T) {
tests := []struct {
name string
input string
want string
}{
{"simple", "Hello World", "hello-world"},
{"multiple spaces", "Hello World", "hello--world"},
{"empty", "", ""},
{"already slug", "hello-world", "hello-world"},
{"unicode", "Cafe\u0301", "cafe"},
{"special chars", "Hello, World!", "hello-world"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := Slugify(tt.input)
if got != tt.want {
t.Errorf("Slugify(%q) = %q, want %q", tt.input, got, tt.want)
}
})
}
}Revisions (0)
No revisions yet.