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 Xxx does 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 test command is run. For more details, run go help test and go 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.

add.go
add_test.go
package main
import (
"testing"
)
// testing add function
func TestAdd(t *testing.T) {
// using two positive numbers
if add(1, 2) != 3 {
t.Errorf("Failed with positive numbers.")
}
// using two negative numbers
if add(-1, -2) != -3 {
t.Errorf("Failed with negative numbers.")
}
}
Copyright ©2024 Educative, Inc. All rights reserved