Skip to main content
Module 9 · Lesson 2 of 542/50 in the course~14 min
Module lessons (2/5)

Table-driven testing

Lesson preview5 hands-on exercises readyCourse Go · Module 9 — Testing, modules and tooling

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 struct slices 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 bool field.
  • Filter individual sub-tests from the CLI with -run TestName/Subtest and 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

  1. 1The table-driven canonical schema
  2. 2Operational Benefits of t.Run
  3. 3Handle expected errors in the table
  4. 4Parallel subtests and loop variables
  5. 5Guided practice
  6. 6Check for understanding
Pro Lesson · Module 9 — Testing, modules and tooling

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.