BackendTooling

Table-driven tests that stay readable

A code editor window floating over a magenta gradient

Table-driven tests are a Go tradition for good reason: adding a case is one line, and the loop body is written once. The trouble starts when the table becomes a spreadsheet nobody wants to read.

func TestSlugify(t *testing.T) {
    tests := map[string]struct {
        in, want string
    }{
        "spaces":     {"Hello World", "hello-world"},
        "symbols":    {"Go & Rust!", "go-rust"},
        "duplicates": {"a  --  b", "a-b"},
    }
    for name, tc := range tests {
        t.Run(name, func(t *testing.T) {
            if got := Slugify(tc.in); got != tc.want {
                t.Errorf("Slugify(%q) = %q, want %q", tc.in, got, tc.want)
            }
        })
    }
}

The version above is about as small as a table gets, and that is the point. Each row says what goes in and what should come out, and the subtest name tells you which row failed.

Habits that help

  • Name every case: a map key or a name field shows up in failure output.
  • Keep only the fields that vary; build the rest in the loop.
  • Split a table when cases need different assertions.
  • Print inputs and outputs in the error message, always.

A test you can read at a glance is a test people will keep up to date. That matters more than squeezing every scenario into a single table.