Welcome to our comprehensive guide on Go *_test.go files! In this tutorial, we'll delve into the world of testing in Go, a powerful tool that helps us ensure our code is bug-free and functional. By the end of this lesson, you'll be well-equipped to write and run tests for your Go projects.
Let's get started! šÆ
*_test.go files?In Go, every package can have a corresponding test file, which ends with _test.go. These files are used to write and run tests for the code present in the main package.
š” Pro Tip: To create a test file for a package called myPackage, you'd name it myPackage_test.go.
To write a test, we create a function that follows a specific pattern:
package myPackage
import "testing"
func TestMyFunction(t *testing.T) {
// Write test code here
}Test (case-sensitive)testing.T as its first argumentTo run the tests, you can use the go test command in your terminal. Go will automatically find and run all test functions in the current directory and its subdirectories.
$ go testAssertions are used to check if the expected output matches the actual output. Go provides several built-in assertion functions in the testing package.
func TestMyFunction(t *testing.T) {
expectedResult := 5
actualResult := MyFunction()
if expectedResult != actualResult {
t.Errorf("Expected %d, but got %d", expectedResult, actualResult)
}
}š Note: The t.Errorf function takes a formatted error message and logs it if the assertion fails.
Go provides several helper functions to test common patterns like:
t.Equal, t.EqualValues)t.Equal)t.NotEqual, t.NotEqualValues)t.Less, t.LessOrEqual, t.Greater, t.GreaterOrEqual)Let's create a simple package with a function to calculate the factorial of a number and write tests for it.
factorial and factorial_test.go)// factorial/factorial.go
package factorial
import "math"
func Factorial(n int) int {
result := 1
for i := 2; i <= n; i++ {
result *= i
}
return result
}// factorial/factorial_test.go
package factorial
import (
"testing"
"fmt"
)
func TestFactorial(t *testing.T) {
tests := []struct {
n int
exp int
}{
{0, 1},
{1, 1},
{2, 2},
{5, 120},
{10, 3628800},
}
for _, test := range tests {
actualResult := Factorial(test.n)
if actualResult != test.exp {
t.Errorf("Test Failed for n = %d. Expected: %d, Got: %d", test.n, test.exp, actualResult)
}
}
}To run the tests, navigate to the factorial directory and execute the go test command:
$ cd factorial
$ go testThe output should show that all tests have passed successfully:
PASS
ok factorial 0.003sWhat is the purpose of the `testing.T` pointer in a Go test function?
What is the significance of the `Test` prefix in a Go test function name?