Go

Table-Driven Tests with t.Run

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A table of test cases looped through `t.Run` gives every case its own name in the output, makes adding new cases trivial, and lets you run individual cases with `-run TestX/case_name`.
Go
Raw
package slugify_test

import (
    "testing"
)

func TestSlugify(t *testing.T) {
    tests := []struct {
        name   string
        input  string
        want   string
    }{
        {"basic",        "Hello, World!",       "hello-world"},
        {"accents",      "Café au lait",        "cafe-au-lait"},
        {"already-slug", "already-slug",        "already-slug"},
        {"empty",        "",                    ""},
        {"only-symbols", "!!!@@@###",           ""},
        {"numbers",      "Top 10 Apps",         "top-10-apps"},
    }

    for _, tc := range tests {
        tc := tc                                  // capture range var (still good practice)
        t.Run(tc.name, func(t *testing.T) {
            t.Parallel()                          // run subtests concurrently
            if got := Slugify(tc.input); got != tc.want {
                t.Errorf("Slugify(%q) = %q, want %q", tc.input, got, tc.want)
            }
        })
    }
}
// go test -run TestSlugify/accents
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.