Module lessons (2/5)
Table-driven testing
The idiomatic pattern: slice of anonymous struct with expected input and output, t.Run(name, ...) per sub-test.
What you'll learn in this lesson
- Structure a table of cases with anonymous
structslices and explicit names. - Create isolated, filterable subtests with
t.Run(tc.name, func(t *testing.T) { ... }). - Model success and failure cases in the same table via the
wantErr boolfield. - Filter individual sub-tests from the CLI with
-run TestName/Subtestand avoid closure traps.
Overview
In Go the idiomatic response to duplication in tests is the table-driven pattern: define an anonymous struct slice with inputs and expected results, and a single loop tests all scenarios via sub-tests t.Run.
Instead of ten almost identical functions, the verification logic lives only once and each new scenario requires only one line in the slice:
Sections covered in this lesson
- 1The table-driven canonical schema
- 2Operational Benefits of
t.Run - 3Handle expected errors in the table
- 4Parallel subtests and loop variables
- 5Guided practice
- 6Check for understanding
Unlock "Table-driven testing" and the full Course Go curriculum
The idiomatic pattern: slice of anonymous struct with expected input and output, `t.Run(name, ...)` per sub-test.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Go plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.