Table-Driven Testing in Go
Testing your code is a crucial step in the development process. However, it can become cumbersome and time-consuming, especially when dealing with a large number of test cases. Manually copying and pasting code to test each case is not a clean solution.
In this article, we will look to table-driven tests in Go to write your test in a fast and efficient way. This approach offers several benefits, including faster test writing, easier maintenance, and improved test coverage.
Why a table?
Table-driven testing is an approach that allows us to define and execute multiple test cases in a straightforward way. The idea is to create a “table” made up of an array of structs, where we can store the input, expected output, and any other relevant information for each test case.
tests := []struct {
// parameter
param1 int
param2 string
param3 interface{} // useful for complex values
// ...
// results
expected1 string
expected2 int
// ...
err error
}{}
Once we have defined our test cases, we can iterate over the array and execute the function under test for each input, verifying that the actual output matches the expected output for each case.
for _, test := range tests {
actual := function(test.param)
assert.Equal(t, test.expected, actual)
}