Go Test: Cleanup with t.Cleanup
In this tutorial, you'll learn about Go Test: Cleanup with t.Cleanup. We cover key concepts, practical examples, and best practices.
Test cleanup -- Use t.Cleanup() to register deferred cleanup functions that run even on test failure.
The Problem
defer in tests may not run if t.Fatal is called. t.Cleanup() registers cleanup that always runs when the test completes, regardless of how it ends.
Wrong
func TestWithServer(t *testing.T) {
s := startTestServer()
defer s.Close() // Not called if t.Fatal occurs!
result := doRequest(s.URL)
if result != "expected" {
t.Fatal("unexpected result") // s.Close() never called!
}
}
Output:
// Server not closed on test failure. Port leak!
Right
func TestWithServer(t *testing.T) {
s := startTestServer()
t.Cleanup(func() { s.Close() }) // Always runs!
result := doRequest(s.URL)
if result != "expected" {
t.Fatal("unexpected result") // Cleanup still runs
}
}
Output:
// Server closed even on test failure. No port leak.
Prevention
- Use t.Cleanup() for resource cleanup
- Runs after test completes regardless of pass/fail
- Multiple cleanups run in LIFO order
- Works with subtests and t.Parallel()
- Use for: server shutdown, DB cleanup, file deletion
Common Mistakes with test cleanup
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro