Nafeem Haque

Software Engineer

10 Mar 2023

Writing Unit Test in Go

Writing unit tests in golang is very easy. In this post we are going to create a simple function called Add. and then write unit test for that function. We are going to use golang’s in built test package. Lets go ahead and start.

  • At first create a directory where you wanna put your codes
  • Initialize go module, I have done as such go mod init calc , but the convention is go mod init github.com/{user}/{repo}
  • Create a file called calc.go and put the following code there.
package calc

func Add(x, y int) int {
	return x + y
}
  • Pretty simple function. Takes two ints and returns an int as a result.
  • Now that we have our function lets create test.
  • Create a file called calc_test.go
  • Lets import the test package as following
package calc

import "testing"
  • Now write the test cases
package calc

import "testing"

var addTestCases = []struct {
	title                string
	num1, num2, expected int
}{
	{
		title:    "adding 1 + 2 should return 3",
		num1:     1,
		num2:     2,
		expected: 3,
	},
	{
		title:    "adding 26 + (-6) should return 20",
		num1:     26,
		num2:     -6,
		expected: 20,
	},
}
  • Okay so we have our test cases, we have given a title so that we know which of the testcase is running, then we have num1,num2 as parameters and finally what we would expect from adding those two numbers
  • Lets write the test function now
package calc

import "testing"

var addTestCases = []struct {
	title                string
	num1, num2, expected int
}{
	{
		title:    "adding 1 + 2 should return 3",
		num1:     1,
		num2:     2,
		expected: 3,
	},
	{
		title:    "adding 26 + (-6) should return 20",
		num1:     26,
		num2:     -6,
		expected: 20,
	},
}

func Test_Add(t *testing.T) {
	for i, testCase := range addTestCases {
		t.Log(i, testCase.title)
		actual := Add(testCase.num1, testCase.num2)
		if testCase.expected != actual {
			t.Fail()
		}
	}
}
  • So we have our full code here, the Test_Add function will loop through the test cases, and send num1,num2 to Add function and compare the returned result with what we have provided as expected. If matched will pass other wise fail.
  • Lets run by go test -v ./ , which means run every test in verbose within this directory.
  • You should get the following output
$ go test -v ./
=== RUN   Test_Add
    calc_test.go:25: 0 adding 1 + 2 should return 3
    calc_test.go:25: 1 adding 26 + (-6) should return 20
--- PASS: Test_Add (0.00s)
PASS
ok      calc   
  • Okay so we have written unit test for a simple function and succeeded with all our cases.

You can experiment with new test cases, as well as try to put wrong expected value to see what happens. That’s all for this post. Happy Coding