~/Golang Unit Testing Quick Guide

Apr 13, 2021


Unit testing in Go uses the built in testing package. You create a file ending with _test.go and define functions with the signature func TestXxx(t *testing.T). Run tests with the go test command.

Example:

1
2
3
4
5
6
// file: mathutil.go
package mathutil

func Add(a, b int) int {
    return a + b
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// file: mathutil_test.go
package mathutil

import "testing"

func TestAdd(t *testing.T) {
    got := Add(2, 3)
    want := 5
    if got != want {
        t.Errorf("Add(2, 3) = %d; want %d", got, want)
    }
}

Run tests:

1
go test

For test coverage use:

1
go test -cover

Use table driven tests to cover multiple scenarios:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
func TestAddTable(t *testing.T) {
    cases := []struct{
        a, b, want int
    }{
        {1, 2, 3},
        {0, 0, 0},
        {-1, 1, 0},
    }
    for _, c := range cases {
        got := Add(c.a, c.b)
        if got != c.want {
            t.Errorf("Add(%d, %d) = %d; want %d", c.a, c.b, got, c.want)
        }
    }
}

For mocks, use testify/mock.

Helpful links: Go test command, Effective Go Testing

Tags: [golang] [testing]