Write files for testing and benchmark in Golang


To write test files in Golang, follow these steps

  1. Create files with suffix _test.go in their names. such as api/api_test.go

  2. For the package name, use the folder name and "_test". For example, api_test.go is in api folder, so the package name will be package api_test

  3. Write functions for testing with prefix Test in every functions. Create a function name similar to this, func TestAdd(), func TestSorting(), func TestBinarySearch(), etc.

  4. Add import "testing" in the files and insert an input parameter in the test functions like this, from func TestAdd() to func TestAdd(t *testing.T)

For benchmark functions, follow the first step and the second step In the third step, use prefix Benchmark instead In the fourth step, use b *testing.B

Then let's create a Go module

mkdir write-test-functions
cd write-test-functions
go mod init gotest

Next, create a function to be used for testing

mkdir operator
cd operator
touch add.go

Add this code in add.go

package operator

func Add(a, b int) int {
	return a + b
}

Now write a test file for this

touch add_test.go
package operator_test

import (
	"testing"

	"github.com/Nuttawut503/golearn/gotest/operator"
)

func TestAdd(t *testing.T) {
	a, b := 1, 1
	want := 0
	got := operator.Add(a, b)
	if got != want {
		t.Errorf("Run Add(%d, %d), want %d but got %d", a, b, want, got)
	}
}

To run the test function, go back to the root directory of this go module and run go test command

go test -v ./...

The console will print the result after running the test functions. Now you can write more functions for testing your own applications. For more information about testing, I recommend this website

Last, let's create a benchmark function. Back to add_test.go, add this code

func BenchmarkAdd(b *testing.B) {
	for i := 0; i < b.N; i++ {
		_ = operator.Add(1_000_000, 1_000_000)
	}
}

When you run benchmark, b.N will be assigned with different values to repeat running your function. After the benchmark is done, it will tell the average time that took each iteration to complete. To run benchmark, type this in your console

go test -bench=. ./...

OK, this is all that will be needed for writing test functions. Thank you for reading.

sources