logo

Go - Testing

Last Updated: 2023-03-24

Go Built-in Testing

To write a new test suite, create a file whose name ends _test.go that contains the func TestXxx().

The file will be excluded from regular package builds but will be included when the go test command is run.

func TestAbs(t *testing.T) {
    got := Abs(-1)
    if got != 1 {
        t.Errorf("Abs(-1) = %d; want 1", got)
    }
}

t.Run enables running "subtests", one for each table entry.

  • testing.T test
  • testing.B benchmark: executed by the "go test" command when its -bench regexp flag is provided
  • testing.F fuzz fuzzing, executed by go test -fuzz

no expect, only error or fatal

  • Error() = Log() + Fail()
  • Errorf() = Logf() + Fail()
  • Fatal() = Log() + FailNow()
  • Fatalf() = Logf() + FailNow()
  • Fail() = the func is failed, but continue execution
  • FailNow() = the func is failed, stop execution (calling runtime.Goexit)
  • Skip() = Log() + SkipNow()
  • Skipf() = Log() + SkipNow()

go-cmp

Use go-cmp to compare objects. For example, to compare Conditions in K8s:

import (
	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
)

ignored = cmpopts.IgnoreFields(metav1.Condition{}, "LastTransitionTime", "ObservedGeneration", "Message")
if diff := cmp.Diff(tc.wantConds, actual.Status.Conditions, ignored); diff != "" {
    t.Errorf("Unexpected status conditions (-want +got):\n%s", diff)
}

Mock

https://github.com/golang/mock