0PricingLogin
Go Academy · Lesson

Table-Driven Tests

Parameterized tests with subtests

What are table-driven tests?

Table-driven tests define a slice of test cases (inputs and expected outputs) and loop over them with a single test body. They reduce duplication and make adding cases trivial.

Basic pattern

Define a struct for each case, loop with t.Run, and report failures with the case name:

tests := []struct {
    name  string
    input int
    want  int
}{
    {"zero", 0, 0},
    {"positive", 3, 9},
    {"negative", -2, 4},
}
for _, tt := range tests {
    t.Run(tt.name, func(t *testing.T) {
        got := Square(tt.input)
        if got != tt.want {
            t.Errorf("Square(%d) = %d; want %d", tt.input, got, tt.want)
        }
    })
}

All lessons in this course

  1. Writing Unit Tests with testing
  2. Table-Driven Tests
  3. Test Doubles: Mocks and Stubs
  4. Test Coverage and testify
← Back to Go Academy