Skip to content

Go Test: Cleanup with t.Cleanup

DodaTech Updated 2026-06-24 1 min read

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!
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

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. 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

**Is t.Cleanup() called after subtests?**

Yes. Each subtest's cleanup runs after the subtest function returns.

What is cleanup order?

Last registered, first executed (LIFO).

Does t.Cleanup() work with t.Parallel()?

Yes. Cleanup runs after all parallel subtests complete.


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