Register a cleanup function with t.Cleanup to ensure resources are released after a test completes.
Use t.Cleanup to register a function that runs after the test finishes, regardless of success or failure.
func TestExample(t *testing.T) {
// Setup
resource := createResource()
// Register cleanup to run after the test
t.Cleanup(func() {
cleanupResource(resource)
})
// Test logic
// ...
}
t.Cleanup lets you schedule a function to run automatically when a test finishes. It ensures resources like files or connections are closed even if the test fails or panics. Think of it as a safety net that always runs your cleanup code, similar to a defer statement but managed by the test runner.