Skip to content

Table-Driven Tests

Master Go’s idiomatic table-driven testing pattern for comprehensive test coverage.

Table-driven tests are a Go testing best practice where you define test cases as a slice of structs, then loop through them. This pattern makes it easy to add new test cases, see all scenarios at a glance, and get clear output using t.Run() for subtests.

Each test case typically includes: a name, inputs, and expected outputs. The t.Run() function creates a subtest that appears separately in test output and can be run individually.

Write table-driven tests for simple calculator functions:

  1. Create a test table for Add function with multiple test cases
  2. Use t.Run() to execute each test case as a subtest
  3. Test the Divide function including error cases (divide by zero)
  4. Cover edge cases like negative numbers and zero values

Table-Driven Testing Pattern

~15 mineasy

Implement comprehensive table-driven tests for calculator functions

  • Table-Driven Pattern: Define test cases as a slice of structs for clarity and maintainability
  • Subtests with t.Run(): Each test case runs as a named subtest with isolated failure reporting
  • Error Testing: Use wantErr boolean field to test both success and error cases
  • Edge Cases: Test boundary conditions (zero, negative numbers, error conditions)
  • Test Naming: Descriptive names make failures easy to understand and debug