Cleanup and TempDir are helper methods for tests in Go.
1func TestWithCleanup(t *testing.T) {2 // t.Cleanup runs AFTER test completion3 t.Cleanup(func() {4 os.RemoveAll("/tmp/test-data")5 fmt.Println("Cleanup completed")6 })78 // Test...9 os.MkdirAll("/tmp/test-data", 0755)10 // ...11}1213// TempDir: automatic creation and deletion of temporary directory14func TestWithTempDir(t *testing.T) {15 dir := t.TempDir() // Creates a temporary directory16 // Automatically removed after test!1718 err := os.WriteFile(filepath.Join(dir, "test.txt"), []byte("hello"), 0644)19 if err != nil {20 t.Fatal(err)21 }2223 data, _ := os.ReadFile(filepath.Join(dir, "test.txt"))24 assert.Equal(t, "hello", string(data))25}2627// Cleanup with execution order (LIFO)28func TestMultipleCleanups(t *testing.T) {29 t.Cleanup(func() { fmt.Println("Cleanup 1") })30 t.Cleanup(func() { fmt.Println("Cleanup 2") })31 t.Cleanup(func() { fmt.Println("Cleanup 3") })32 // Output: Cleanup 3, Cleanup 2, Cleanup 1 (LIFO)33}3435// t.Setenv: automatic environment variable restoration36func TestWithEnv(t *testing.T) {37 t.Setenv("DATABASE_URL", "postgres://localhost/test")38 // DATABASE_URL is set only for this test39 // Automatically restored after test4041 url := os.Getenv("DATABASE_URL")42 assert.Equal(t, "postgres://localhost/test", url)43}
Advantages: