Writing Unit Tests in Go — Basics

Zaid Afzal ⚡️
1 min readJan 4, 2023

Unit tests are functions that are designed to test small units of functionality in your code.

To write a unit test in Go, you will need to:

  1. Declare a function with a name that starts with “Test” and has a single argument of type “testing.T”. This function will contain your test case.
  2. Within the test function, use the various methods provided by the “testing” package to perform checks on the behavior of your code. For example, you can use the “assert.Equal” or “assert.NotEqual” method to fail the test if a certain condition is not met.
  3. Run the test using the “go test” command.

Here is an example of a unit test in Go:

package mypackage

import "testing"

func TestSum(t *testing.T) {
result := sum(1, 2)
expected := 3
assert.Equal(t, expected, result)
}

This test function will test the “sum” function in the “mypackage” package by calling it with the arguments 1 and 2 and checking that the result is 3. If the result is not 3, the test will fail with an error message.

--

--