Table-Driven Tests
Table-Driven Tests
Section titled “Table-Driven Tests”Master Go’s idiomatic table-driven testing pattern for comprehensive test coverage.
Background
Section titled “Background”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.
Your Task
Section titled “Your Task”Write table-driven tests for simple calculator functions:
- Create a test table for
Addfunction with multiple test cases - Use
t.Run()to execute each test case as a subtest - Test the
Dividefunction including error cases (divide by zero) - Cover edge cases like negative numbers and zero values
Table-Driven Testing Pattern
~15 mineasy
Implement comprehensive table-driven tests for calculator functions
Key Concepts
Section titled “Key Concepts”- 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
wantErrboolean 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