What is built-in testing support in GO?
In this shot, we will learn how to test your code in Go. Go has built-in support for testing using the testing package.
Usage
Package testing provides support for automated testing of Go code. It intended to be used with the go test command that automates the execution of any function of the following form:
func TestXxx(*testing.T)
Where
Xxxdoes not start with a lowercase letter and the function name identifies the test routine.
Within these functions, use Error, Fail, or related methods to signal failure.
Writing tests
Create a file that contains the TestXxx functions described above and whose name ends with _test.go to write a new test suite and place it in the same package as the one being tested.
A typical unit test will look something like this:
import "testing"
func TestAbc(t *testing.T) {
t.Error() // indicate test failed
}
The test file will be included when the
go testcommand is run. For more details, rungo help testandgo help testflag.
Code
Let’s write a simple unit test using the testing package.
We will test an add function to check if it correctly adds two integers.
package mainimport ("testing")// testing add functionfunc TestAdd(t *testing.T) {// using two positive numbersif add(1, 2) != 3 {t.Errorf("Failed with positive numbers.")}// using two negative numbersif add(-1, -2) != -3 {t.Errorf("Failed with negative numbers.")}}
Free Resources