go / intermediate
Snippet
Deferred Cleanup Registration in Unit Tests Using the Cleanup Method
Unlike defer statements which execute at the end of the surrounding block, `t.Cleanup` registers teardown functions that execute after the test (and all its subtests) completes. This is particularly useful in test helpers where the setup code doesn't share the same function scope as the test runner.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package mainimport ("fmt""testing")func TestDatabaseConnection(t *testing.T) {dbName := "test_db"t.Cleanup(func() {fmt.Printf("Cleaning up database: %s\n", dbName)})fmt.Println("Database setup complete.")}
Breakdown
1
t.Cleanup(func() {
Registers a function to be executed automatically when this test finishes.
2
fmt.Printf("Cleaning up database: %s\n", dbName)
The cleanup logic, guaranteed to run even if the test fails or exits early.