To write unit tests in Go, you need to follow a specific naming convention and structure for your test files and functions. Additionally, you will be using the ‘testing‘ package provided by the Go standard library.
Here are the steps to write a simple unit test in Go:
1. Create a new test file with the same name as the file you want to test, but with a ‘_test.go‘ suffix. If your file is named ‘math.go‘, your test file should be ‘math_test.go‘.
2. Import the ‘testing‘ package at the beginning of the test file.
3. Write test functions that follow the naming convention ‘TestXxx(t *testing.T)‘, where ‘Xxx‘ is the name of the function you want to test.
4. Use the ‘t‘ testing object to perform assertions and report any errors by calling its ‘Error‘ or ‘Errorf‘ methods.
5. Run ‘go test‘ in your terminal to execute your tests.
Here’s an example for writing unit tests for a simple ‘Add‘ function defined in a file ‘math.go‘:
File: ‘math.go‘
package main
func Add(a, b int) int {
return a + b
}
File: ‘math_test.go‘
package main
import (
"testing"
)
func TestAdd(t *testing.T) {
cases := []struct {
a, b, expected int
}{
{1, 2, 3},
{4, 6, 10},
{-1, 2, 1},
{-4, -6, -10},
}
for _, tc := range cases {
result := Add(tc.a, tc.b)
if result != tc.expected {
t.Errorf("Add(%d, %d) = %d; expected %d", tc.a, tc.b, result, tc.expected)
}
}
}
In this example, we have defined a ‘TestAdd‘ function with various test cases, and then performed the assertions checking the returned result of the ‘Add‘ function against the expected values.
To run these tests, execute the command ‘go test‘ in your terminal. If all tests pass, you will see a message like ‘PASS‘, otherwise, you will see the error messages reported by the ‘t.Errorf‘ method.
You can use other methods from the ‘*testing.T‘ struct like ‘t.Fatal‘ or ‘t.Fatalf‘ when you want to stop the execution of the test immediately after reporting an error.