Go: Test Cleanup in Go 1.14

In Go 1.14, the new T.Cleanup() function schedules defer-like work to be done after the current test. This makes it possible to write very comfortable setup helper functions:

func SetUpFrobnicator(t *testing.T) *frob.Frobnicator {

    f := frob.New()    // Do setup.
    t.Cleanup(f.Close) // Schedule cleanup for later.
    return f

func TestFoobar(t *testing.T) {
    f := SetUpFrobnicator(t)

    // (Run the test itself, using f.)

Previously, presumably the most idiomatic thing would have been to return a “cancel” callback from the helper function and rely on the test to defer it.

I’m almost a bit surprised that the Go test framework offers this now - otherwise, compared to other languages, Go’s test code is very similar in style to production code (e.g. it doesn’t even have assert functions).

Related articles on this blog: