- Published on
Test Table
- Authors
- Name
- Galuh Pradipta
Tutorial: Writing Unit Tests in Go with Test Table
Unit testing is a crucial part of software development that ensures the quality of code. Go has an inbuilt testing package that makes testing easier and efficient. In this tutorial, we will learn how to write unit tests in Go using the test table.
What is a Test Table in Go?
A test table is a way of testing Go functions with different input parameters and expected outputs. It is a convenient way of writing tests for functions with multiple test cases. The test table is defined as a slice of structs, where each struct represents a test case with input parameters and corresponding expected output.
Writing a Function to Test
Let's consider an example function that adds two integers and returns their sum:
func Add(a, b int) int {
return a + b
}
Writing a Test Table
To write a test table for the Add
function, we can create a slice of structs, where each struct represents a test case with input parameters and expected output. Here's an example:
var testCases = []struct {
a, b int
expected int
}{
{2, 3, 5},
{-1, 1, 0},
{0, 0, 0},
{999, 1, 1000},
}
In the above code snippet, we have defined a slice of structs with four test cases. Each struct has two input parameters a
and b
, and an expected output expected
.
Writing Tests with the Test Table
To write tests with the test table, we use the t.Run()
function to execute each test case. Here's an example:
func TestAdd(t *testing.T) {
for _, tc := range testCases {
actual := Add(tc.a, tc.b)
if actual != tc.expected {
t.Errorf("Add(%d, %d): expected %d, but got %d", tc.a, tc.b, tc.expected, actual)
}
}
}
In the above code snippet, we have defined a test function TestAdd
that iterates through each test case in the testCases
slice and executes the Add
function with the input parameters. We then compare the actual output with the expected output and use the t.Errorf()
function to log an error if the test fails.
Running the Test
To run the test, we can use the go test
command in the terminal. Here's an example:
$ go test
If all the tests pass, we should see an output like this:
PASS
ok _/path/to/package 0.001s
Also there’s awesome open-source library for generating test.
https://github.com/cweill/gotests
Conclusion
In this tutorial, we learned how to write unit tests in Go using the test table. We first defined a test table with multiple test cases, each with input parameters and expected output. We then wrote a test function that iterates through each test case and executes the function under test with the input parameters. Finally, we ran the test using the go test
command and checked the output for any failures.
Happy testing!