Go - Testing
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.Ttesttesting.Bbenchmark: executed by the "go test" command when its-bench regexpflag is providedtesting.Ffuzz fuzzing, executed bygo 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 executionFailNow()= 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)
}