DevPath
Mid lesson · 12 min

Write table-driven tests with useful names

Cover edge cases while keeping each failure easy to diagnose.

Describe the rule

A table-driven test suits a function with many inputs and one behavior. Each case should have a name, input, and expected result. Put genuinely different workflows in separate tests; a giant table with many optional fields can be harder to understand than a few focused tests.

Run cases independently

Use t.Run so the failing case is named. If a case mutates a slice or map, copy shared inputs before reuse. Assert both the returned value and the error contract. For an error category, errors.Is is more stable than comparing the full message.

for _, tc := range tests {
    t.Run(tc.name, func(t *testing.T) {
        got, err := Parse(tc.input)
        // Compare got and the expected error for this case.
    })
}

Choose meaningful boundaries

Include empty input, the smallest valid value, one over the limit, and malformed input. A test that repeats the implementation's algorithm can approve the same mistake. Prefer a small example whose expected answer can be checked independently.

Check your understanding

Why name each table-driven case?

Show explanation

The failure output identifies the exact scenario, so the rule that broke is easier to diagnose.

Put this lesson into practice

A practice activity at this level in the same module.

Try: Depend on an interface, not a struct

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.