Questions
I would like to know the use case of t.Cleanup
introduced in Go1.14. What is the convenience of t.Cleanup as compared to using defer?
https://golang.org/pkg/testing/#T.Cleanup.
- Sample
For example, let's say we create a temporary directory, and when we test it, we want to delete the temporary directory we created.
t.Cleanup
can be used to write a test as follows, but it also works as defer os.RemoveAll(tempDir)
.
package mypkg
import (
"io/ioutil"
"os"
"testing"
)
func TestDirwalk(t *testing.T) {
tempDir, err := ioutil.TempDir(".", "temp")
if err != nil {
t.Errorf("create tempDir: %v", err)
}
t.Cleanup(func() { os.RemoveAll(tempDir) })
// something...
}
Cleanup functions are also called if your test panics, so in your case both would work.
The advantage of using
T.Cleanup()
becomes clear if your test calls other functions, passingtesting.T
along. Obviously usingdefer
in those functions would be executed before those functions return, but if you register cleanup functions usingT.Cleanup()
, then they will be called only at the end of your test.Think of
T.Cleanup()
as an "improved" and extended version ofdefer
. It also documents that the passed functions are for cleanup purposes.