Go testing patterns for production-grade code: subtests, test helpers, fixtures, golden files, httptest, testcontainers, fuzz testing, and testing/synctest. Covers mocking strategies, test isolation, coverage analysis, and test design philosophy.
Ships in go-agent-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Tests are production code. They run in CI on every commit, they document behavior, and they're the first thing you read when a function breaks at 3am. Write them with the same care you'd give to code that handles money.
Community default. A project skill or agent-config rule that explicitly supersedes
go-test-qualitytakes precedence over this one.
Detailed reference material, loaded on demand:
references/helpers-and-fixtures.md — test helpers, factory functions
with options, t.Cleanup, golden files, mock implementations.references/integration-testing.md — httptest recorder and server,
testcontainers, build tags, TestMain, fuzz testing.references/concurrency-and-benchmarks.md — synctest, goleak,
t.Context(), b.Loop() benchmarks, t.Attr and artifacts.Read a reference file only when the summary below is not enough.
// ✅ Good — tests what the function DOES
func TestTransferFunds_InsufficientBalance(t *testing.T) {
from := NewAccount("alice", 100)
to := NewAccount("bob", 0)
err := TransferFunds(from, to, 150)
require.ErrorIs(t, err, ErrInsufficientFunds)
assert.Equal(t, 100, from.Balance(), "sender balance should be unchanged")
assert.Equal(t, 0, to.Balance(), "receiver balance should be unchanged")
}
// ❌ Bad — tests HOW the function does it
// asserts debit() was called before credit(), rollback() was called,
// internal mutex was locked — breaks on every refactor
Multiple assert calls are fine when they verify different facets of the
SAME behavior (both accounts after a transfer). A test that checks creation
AND update AND deletion is three tests pretending to be one.
When the test fails, the name alone should say what broke:
// ✅ Good — reads like a sentence
func TestOrderService_Cancel_RefundsPartiallyShippedItems(t *testing.T) { ... }
func TestParseConfig_ReturnsErrorOnMissingRequiredField(t *testing.T) { ... }
// ❌ Bad — says nothing useful
func TestCancel(t *testing.T) { ... }
func TestRateLimiter_Success(t *testing.T) { ... }
_test.go per source file (parser.go → parser_test.go), tests
in the order of the functions they cover — tools and reviewers navigate
by file.pkg_test package so they can only use
what callers can; white-box tests stay in pkg.//go:build integration.Use t.Run to group related scenarios under a parent test. Each subtest
gets its own setup, its own failure, and its own name in CI output:
func TestUserService_Create(t *testing.T) {
svc := setupUserService(t)
t.Run("succeeds with valid input", func(t *testing.T) {
user, err := svc.Create(ctx, CreateUserInput{Name: "Alice", Email: "[email protected]"})
require.NoError(t, err)
assert.NotEmpty(t, user.ID)
})
t.Run("rejects duplicate email", func(t *testing.T) {
_, _ = svc.Create(ctx, CreateUserInput{Name: "Alice", Email: "[email protected]"})
_, err := svc.Create(ctx, CreateUserInput{Name: "Bob", Email: "[email protected]"})
require.ErrorIs(t, err, ErrDuplicateEmail)
})
}
t.Helper() in test utilities so failures point to the
caller, not the helper.t.Cleanup over defer — it runs even after t.FailNow()
and is scoped to the test, not the function.Full implementations in references/helpers-and-fixtures.md.
| Situation | Approach | Details |
|---|---|---|
| Pure function, 3+ data cases | Table-driven test | go-test-table-driven skill |
| HTTP handler in isolation | httptest.NewRecorder + mock store | references/integration-testing.md |
| Full routing/middleware stack | httptest.NewServer | references/integration-testing.md |
| Real database behavior | testcontainers + build tags | references/integration-testing.md |
| Complex output (JSON, HTML, SQL) | Golden files in testdata/ | references/helpers-and-fixtures.md |
| Parser/validator on untrusted input | Fuzz test | references/integration-testing.md |
now func() time.Time).func TestSlugify(t *testing.T) {
t.Parallel() // safe: pure function, no shared state
// ...
}
Do NOT use t.Parallel() when tests share mutable state, databases,
files, or process-level state — t.Setenv and t.Chdir panic in a
parallel test for exactly that reason.
go test -race -coverprofile=coverage.out -coverpkg=./... ./...
go tool cover -html=coverage.out # read the red lines, not the percentage
Coverage finds untested code; it does not measure whether the assertions
are any good. Use it to locate gaps, and let CI enforce a floor that only
ratchets up (the go-ci skill owns the gate). Without -coverpkg, a
package exercised only by another package's tests reports 0%.
time.Sleep — it is slow when it works and
flaky when it does not.synctest.Test. The bubble's
fake clock advances instantly once every goroutine is blocked, and
synctest.Wait() replaces "sleep until the background goroutine gets
there". On Go 1.24 the API is synctest.Run behind
GOEXPERIMENT=synctest. Go 1.27 adds synctest.Sleep(d) (advance and
settle in one call) and httptest.NewTestServer(t, h), an in-memory
server that works inside the bubble and closes itself.goleak.VerifyTestMain(m) in TestMain, or defer goleak.VerifyNone(t).
-race finds data races; it does not find a goroutine that never exits.t.Context() (Go 1.24+) instead of context.Background() — it is
cancelled before t.Cleanup runs, so blocked work unwinds when the test
ends.for b.Loop() (Go 1.24+): setup runs once, results stay
alive without a sink. Add b.ReportAllocs() and compare runs with
benchstat.t.Attr (Go 1.25+) emits key/value pairs CI can parse;
t.ArtifactDir() with go test -artifacts (Go 1.26+) keeps failing
golden output or captured bodies outside the repository.Examples for both sections: references/concurrency-and-benchmarks.md.
assert.New(t) / require.New(t) inside each t.Run. An
instance created from the parent t reports a subtest's failure against
the parent, and the failing subtest itself prints PASS.require, t.Fatal and t.FailNow only on the test goroutine.
From a spawned goroutine they cannot stop the test. Send results back on
a channel and assert after receiving. go vet's testinggoroutine and
golangci-lint's testifylint catch most cases.require for preconditions, assert for independent checks — a
failed precondition should stop the test before it nil-panics.assert.Eventually hides timing bugs in polling; prefer synctest.time.Sleep for synchronization — use testing/synctest, channels, or pollingTest1, TestSuccess — name the scenariocontext.Background() in a test — use t.Context()for range b.N on Go 1.24+ — use for b.Loop()t.Helper() called in every test utility functiont.Cleanup() used for resource teardownt.Parallel() used where safe, avoided where nottesting.Short() or build tagstime.Sleep for synchronization anywhere in the suitegoleakfor b.Loop() and call b.ReportAllocs()go test -race ./... passesrequire off the test goroutineWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
35 skills in this plugin
/git-commitStructured git commit messages following Conventional Commits format for Go projects. Generates well-scoped, atomic commits with clear descriptions. Use when committing changes, writing commit messages, preparing PRs, or reviewing commit history quality. Trigger examples: "commit these changes", "create commit", "commit message", "prepare PR", "squash commits". Not for: code review (go-code-review), changelog generation.
/go-api-designHTTP/REST API design for Go services: handlers, ServeMux routing, middleware, request validation, pagination, idempotency, health checks, error responses, and graceful shutdown. Use when designing APIs, writing HTTP handlers, implementing middleware, or structuring REST endpoints. Trigger examples: "design API", "REST endpoints", "HTTP handler", "middleware pattern", "graceful shutdown", "API versioning". Not for: gRPC services (go-grpc), spec-first OpenAPI work (go-openapi), general architecture (go-architecture-review), concurrency in handlers (go-concurrency-review).
/go-architecture-reviewReview Go project architecture: package structure, dependency direction, layering, separation of concerns, domain modeling, and module boundaries. Use when reviewing architecture, designing package layout, evaluating dependency graphs, or refactoring monoliths into modules. Trigger examples: "review architecture", "package structure", "project layout", "dependency direction", "clean architecture Go", "module boundaries". Not for: code-level style (go-coding-standards), endpoint design (go-api-design).
/go-agent-skills:go-test-qualityfrom go-agent-skills
npx claudepluginhub eduardo-sl/go-agent-skills --plugin go-agent-skillsOther plugins' skills for the same job