Deferred teardown closure in Go testing
While watching Mitchell Hashimoto’s excellent talk1 on Go testing, I came across this neat technique for deferring teardown to the caller. Let’s say you have a helper function in a test that needs to perform some cleanup afterward. You can’t run the teardown inside the helper itself because the test still needs the setup. For example, in the following case, the helper runs its teardown immediately: func TestFoo(t *testing.T) { helper(t) // Test logic here: resources may already be cleaned up! } func helper(t *testing.T) { t.Helper() // Setup code here. // Teardown code here. defer func() { // Clean up something. }() } When helper is called, it defers its teardown—which executes at the end of the helper function, not the test. But the test logic still depends on whatever the helper set up. So this approach doesn’t work. ...