Table-driven tests are a powerful and efficient technique for writing unit tests in Go. They allow developers to create comprehensive test suites with minimal code duplication.
Table-driven tests involve defining a slice of test cases, each containing input data and expected output. The test function then iterates through these cases, running the same test logic for each one.
A typical table-driven test in Go consists of three main components:
Let's look at an example of a table-driven test for a function that adds two integers:
package main
import "testing"
func Add(a, b int) int {
return a + b
}
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"positive numbers", 2, 3, 5},
{"negative numbers", -2, -3, -5},
{"mixed numbers", -2, 3, 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Add(tt.a, tt.b)
if result != tt.expected {
t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, result, tt.expected)
}
})
}
}
In this example, we define a slice of test cases, each with a name, input values, and expected output. The test function then iterates through these cases, running the Add
function and comparing the result to the expected value.
t.Run()
for subtests to improve output readabilityTable-driven tests can be extended to handle more complex scenarios:
Table-driven tests integrate seamlessly with Go's built-in testing package. They can be used alongside other testing techniques to create comprehensive test suites.
Table-driven tests are an essential tool in Go programming. They enhance test maintainability, readability, and coverage. By mastering this technique, developers can create more robust and efficient test suites for their Go projects.
To further improve your Go testing skills, explore related concepts such as Go Unit Testing and Go Test Coverage.