testing#
The testing package provides support for automated testing of Go packages. It is intended to be used in concert with the go test command.
Test Functions#
func TestXxx(t *testing.T)- Test functions must start with
Testfollowed by a capitalized identifier - Must accept a single parameter of type
*testing.T
Key Methods#
t.Fail(): Marks the test as failed, but continues executiont.FailNow(): Marks the test as failed and stops execution of the current goroutine immediately viaruntime.Goexit()t.Errorf(format string, args ...any): Equivalent tot.Logf+t.Fail(). Logs an error and marks the test as failed, but continues executiont.Fatalf(format string, args ...any): Equivalent tot.Errorf+t.FailNow()(t.Logf+t.FailNow()). Logs an error and stops execution of the current test goroutine immediatelyt.Skip(args ...any): Marks the test as skipped and stops execution immediatelyt.Helper(): Marks the calling function as a test helper. When printing file and line information in test failures, the line inside the helper function is skipped, reporting the caller’s line insteadt.Cleanup(f func()): Registers a teardown function (eg. closing DB connections, releasing RPC clients) that executes in LIFO order aftert.Context()is canceled. See Cleanupt.Context() context.Context: Returns a context that is automatically canceled as soon as the test body finishes (beforet.Cleanupcallbacks run). See Test Contexts
Failure Handling in Goroutines#
t.Fatalf and t.FailNow call runtime.Goexit(), which only terminates the calling goroutine. Never call t.Fatalf or t.FailNow inside a background goroutine (go func()); doing so leaves the main test goroutine running or hanging and violates go vet. Always use t.Errorf followed by return inside worker goroutines.
// Correct: Record failure with t.Errorf and return from worker goroutine
go func() {
if err := doAsyncWork(); err != nil {
t.Errorf("doAsyncWork() failed: %v", err)
return
}
}()
// Prohibited: t.Fatalf in a child goroutine does not stop the main test goroutine
go func() {
if err := doAsyncWork(); err != nil {
t.Fatalf("doAsyncWork() failed: %v", err) // Violates go vet
}
}()Test Contexts (t.Context())#
Starting in Go 1.24, *testing.T provides t.Context(), returning a context.Context that is automatically canceled when the test or subtest finishes.
Internally, t.Context() is created via context.WithCancel, but the cancel function is exclusively owned by the go test framework and automatically invoked when the test body finishes. Returning only context.Context (without CancelFunc) prevents test helpers or sub-functions from prematurely canceling the entire test’s root context. To test early cancellation, derive a child context via ctx, cancel := context.WithCancel(t.Context()).
Lifecycle & Cancellation Order#
Understanding when t.Context() is canceled relative to t.Cleanup is critical for avoiding teardown errors:
t.Runstarts and initializest.Context()- Test function body executes
- Test function body returns normally or exits early via
t.Fatalf/t.FailNow t.Context()is automatically canceled (<-ctx.Done()closes)- Registered
t.Cleanupcallbacks execute in LIFO order - Test completes and final status is reported
Subtest Scope (Innermost Context)#
Always use the innermost t.Context() inside subtests (t.Run) rather than sharing a parent test context.
// Correct: Subtest-scoped context
func TestService(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := service.Fetch(t.Context(), tc.id)
...
})
}
}
// Prohibited: Shared parent context leaks lifecycle across subtests
func TestService(t *testing.T) {
ctx := t.Context() // Outer scope
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := service.Fetch(ctx, tc.id)
})
}
}Context Derivation & Single Source of Truth#
When a test modifies the context (e.g., adding timeouts or metadata) or passes the context to multiple functions, capture ctx := t.Context() at the beginning of the test as the single source of truth.
// Correct: Single source of truth preserved
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
db := setupDB(ctx, t)
got, err := service.Process(ctx, tc.input)
})
// Antipattern: Calling t.Context() repeatedly bypasses derived timeouts
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
db := setupDB(t.Context(), t) // Timeout bypassed
got, err := service.Process(t.Context(), tc.input) // Timeout bypassed
})Helper Function Signatures#
Test helpers, fixtures, and test doubles must accept ctx context.Context as an explicit first parameter rather than calling t.Context() internally. This allows callers to pass customized contexts (e.g. earlier deadlines or cancelable contexts).
// Correct: Explicit context parameter
func setupDatabase(ctx context.Context, t *testing.T) *Database {
t.Helper()
return newTestDatabase(ctx, t)
}
// Prohibited: Internal context extraction
func setupDatabase(t *testing.T) *Database {
t.Helper()
return newTestDatabase(t.Context(), t)
}Table-Driven Tests#
Table-driven tests organize test cases in a slice of anonymous structs, enabling clean test additions and parameterized runs.
func TestCalculate(t *testing.T) {
tests := []struct {
name string
input int
want int
wantErr bool
}{
{
name: "positive number",
input: 5,
want: 10,
},
{
name: "negative number returns error",
input: -1,
wantErr: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := Calculate(tc.input)
if (err != nil) != tc.wantErr {
t.Fatalf("Calculate(%d) error = %v, wantErr %v", tc.input, err, tc.wantErr)
}
if got != tc.want {
t.Errorf("Calculate(%d) = %d, want %d", tc.input, got, tc.want)
}
})
}
}Parallel Subtests#
Use t.Parallel() inside t.Run to run subtests concurrently.
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
got := LongRunningTask(t.Context(), tc.input)
...
})
}Cleanup (t.Cleanup)#
t.Cleanup registers functions to be called when the test (or subtest) completes. Cleanup functions run in LIFO (last-in, first-out) order.
func TestResource(t *testing.T) {
f := createTempFile(t)
t.Cleanup(func() {
os.Remove(f.Name())
})
}Context in Cleanup:
t.Context()is canceled beforet.Cleanupcallbacks run. For cleanup operations requiring active network or database calls, usecontext.Background()orcontext.WithoutCancel(t.Context()).
Creating Contexts in Cleanup#
Because t.Context() is already canceled when t.Cleanup executes, any teardown call (eg. closing an RPC client or dropping test database tables) that accepts a context requires a new active context:
context.Background(): Creates a completely new, empty root contextcontext.WithoutCancel(t.Context()): Creates a new derived context that ignores parent cancellation while preserving context values (eg. trace IDs, auth metadata, logger fields) attached tot.Context()- Wrap the cleanup context with
context.WithTimeoutto prevent teardown operations from hanging indefinitely
func TestDatabaseTeardown(t *testing.T) {
db := setupDatabase(t.Context(), t)
t.Cleanup(func() {
// Derive a non-canceled context preserving values, bounded by a timeout
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(t.Context()), 5*time.Second)
defer cancel()
if err := db.Close(cleanupCtx); err != nil {
t.Errorf("db.Close() failed during cleanup: %v", err)
}
})
}