Map

T.Context in Go Testing

Wiki summarygolangtestingcontext โ†ณ show in map Markdown
title
T.Context in Go Testing
type
summary
summary
Jonathan Hall's quick reader-prompted note on when to use Go 1.24's testing.T.Context (and when not to)
tags
golang, testing, context
created
2026-04-25
updated
2026-04-25

Short reader-question post by Jonathan Hall on boldlygo-tech, following up on his earlier piece about context.TODO(). Bruno Schaatsbergen asked why Hall hadn't recommended Go 1.24's new T.Context() / B.Context() / F.Context() methods. Hall's honest answer: he forgot. The longer answer is the actual content of the post.

What the methods do

Go 1.24 added Context() methods to testing.T, testing.B, and testing.F. Each returns a context.Context whose cancellation is tied to the lifetime of that specific test, benchmark, or fuzz target. When the test finishes (or is canceled), the context is canceled โ€” so any goroutines that ran with that context get the cancellation signal automatically, no manual cleanup needed.

This replaces the common pattern of writing ctx, cancel := context.WithCancel(context.Background()) and t.Cleanup(cancel) in every test that needs a context.

Hall's recommendation

For most normal tests, use T.Context(). It's the right default โ€” scoped to the test, automatic cleanup, no boilerplate.

The exception is anything whose lifetime is broader than a single test. The two examples Hall calls out:

  • A test server started in TestMain or in a shared setup, used by many tests
  • A Docker container started via Testcontainers or similar, shared across the whole test binary

Using T.Context() for these would shut them down as soon as the first test that touched them finishes โ€” which is wrong for shared resources. For those cases, use context.Background() (or a higher-level context that lives at the package or TestMain level) and manage cancellation explicitly.

The general rule

Match the lifetime of the context to the lifetime of the thing that owns it. T.Context() owns "this single test"; if you want something to outlive that, you need a context whose owner does too.