go-test-quality
Skill85 starsChanged 18 days agoMITView on GitHub
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. Use when writing tests, improving coverage, reviewing test quality, setting up test infrastructure, or choosing a testing approach. Trigger examples: "add tests", "improve coverage", "write tests for this", "test helpers", "mock this dependency", "integration test", "fuzz test", "flaky test", "synctest", "goroutine leak in tests". Not for: benchmarking methodology (go-performance-review), security testing (go-security-audit), table-driven patterns (go-test-table-driven).
We split this skill into the rules it gives an agent
9 rules. About 0 are common, 6 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 28
Write them with the same care you'd give to code that handles money.
- Distinctive: line 42
Read a reference file only when the summary below is not enough.
- Distinctive: line 74
When the test fails, the name alone should say what broke:
- Very specific: line 97
Use t.Run to group related scenarios under a parent test.
- Distinctive: line 147
If you mock everything, you're testing your mocks, not your code.
- Very specific: line 158
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 …
- Very specific: line 174
Never synchronise a test with time.Sleep — it is slow when it works and flaky when it does not.
- Distinctive: line 231
Every test has meaningful assertions (no empty test bodies)
- Distinctive: line 232
Test names describe the scenario, not the method
≈ “Common” is an estimate: at least 1 in 5 of the 308,232 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Go Test Quality
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.Attrand artifacts.
Read a reference file only when the summary below is not enough.
1. Test Design Philosophy
Test behavior, not implementation
// ✅ 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 refactorOne assertion per logical concept
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.
Name tests like bug reports
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) { ... }Layout
- One
_test.goper source file (parser.go→parser_test.go), tests in the order of the functions they cover — tools and reviewers navigate by file. - Public-API tests live in the
pkg_testpackage so they can only use what callers can; white-box tests stay inpkg. - Integration tests sit behind
//go:build integration.
2. Subtests for Organized Scenarios
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: "alice@example.com"})
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: "taken@example.com"})
_, err := svc.Create(ctx, CreateUserInput{Name: "Bob", Email: "taken@example.com"})
require.ErrorIs(t, err, ErrDuplicateEmail)
})
}3. Test Helper Rules
- Always call
t.Helper()in test utilities so failures point to the caller, not the helper. - Factory functions with functional options for complex test objects — defaults with per-test overrides, never a 15-parameter constructor.
- Prefer
t.Cleanupoverdefer— it runs even aftert.FailNow()and is scoped to the test, not the function.
Full implementations in references/helpers-and-fixtures.md.
4. Choosing the Test Type
| 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 |
5. Mocking Rules
- Interface-based hand-written mocks for small interfaces (≤3 methods): a struct with function fields plus recorded calls.
- Function injection for simple seams (
now func() time.Time). - Do NOT mock: value objects, pure functions, the standard library, or your own code in the same package. Test the real thing.
- If you mock everything, you're testing your mocks, not your code.
6. Parallelism and Coverage
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 percentageCoverage 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%.
7. Testing Concurrent Code
- Never synchronise a test with
time.Sleep— it is slow when it works and flaky when it does not. - Go 1.25+: run time-dependent code inside
synctest.Test. The bubble's fake clock advances instantly once every goroutine is blocked, andsynctest.Wait()replaces "sleep until the background goroutine gets there". On Go 1.24 the API issynctest.RunbehindGOEXPERIMENT=synctest. Go 1.27 addssynctest.Sleep(d)(advance and settle in one call) andhttptest.NewTestServer(t, h), an in-memory server that works inside the bubble and closes itself. - Any package that starts goroutines verifies none leak:
goleak.VerifyTestMain(m)inTestMain, ordefer goleak.VerifyNone(t).-racefinds data races; it does not find a goroutine that never exits.
8. Test Context, Benchmarks, and Artifacts
t.Context()(Go 1.24+) instead ofcontext.Background()— it is cancelled beforet.Cleanupruns, so blocked work unwinds when the test ends.- Benchmarks use
for b.Loop()(Go 1.24+): setup runs once, results stay alive without a sink. Addb.ReportAllocs()and compare runs withbenchstat. t.Attr(Go 1.25+) emits key/value pairs CI can parse;t.ArtifactDir()withgo test -artifacts(Go 1.26+) keeps failing golden output or captured bodies outside the repository.
Examples for both sections: references/concurrency-and-benchmarks.md.
9. Assertion Library Traps
- Build
assert.New(t)/require.New(t)inside eacht.Run. An instance created from the parenttreports a subtest's failure against the parent, and the failing subtest itself printsPASS. require,t.Fatalandt.FailNowonly 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'stestinggoroutineand golangci-lint'stestifylintcatch most cases.requirefor preconditions,assertfor independent checks — a failed precondition should stop the test before it nil-panics.assert.Eventuallyhides timing bugs in polling; prefersynctest.
Anti-Patterns
- 🔴 Test with no assertions — always passes, proves nothing
- 🔴
time.Sleepfor synchronization — usetesting/synctest, channels, or polling - 🔴 Test depends on execution order — each test must stand alone
- 🔴 Mocking everything — you end up testing your mocks, not your code
- 🟡 Test names like
Test1,TestSuccess— name the scenario - 🟡 Reaching into private fields — test through the public API
- 🟡 No edge cases: empty, nil, zero, max values, unicode
- 🟡 Giant shared setup — each test should set up only what it needs
- 🟡
context.Background()in a test — uset.Context() - 🟡
for range b.Non Go 1.24+ — usefor b.Loop() - 🟢 Fuzz anything that takes untrusted input
- 🟢 Golden files for complex output comparisons
Verification Checklist
- Every test has meaningful assertions (no empty test bodies)
- Test names describe the scenario, not the method
t.Helper()called in every test utility functiont.Cleanup()used for resource teardownt.Parallel()used where safe, avoided where not- Integration tests guarded with
testing.Short()or build tags - Mocks are minimal — only mock external dependencies
- No
time.Sleepfor synchronization anywhere in the suite - Packages that start goroutines verify with
goleak - Benchmarks use
for b.Loop()and callb.ReportAllocs() - Edge cases covered: empty, nil, zero, boundary values
go test -race ./...passes- Coverage is used to find gaps; CI enforces a ratcheting floor, not a target
- testify instances are built per subtest; no
requireoff the test goroutine
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- rjansen/skills★ 1same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository38 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- .cursor/rules/go-skills.mdcCursor rule
- go-api-designSkill
- go-architecture-reviewSkill
- go-cliSkill
- go-dependency-injectionSkill
- go-design-patternsSkill
- go-graphqlSkill
- go-grpcSkill
- go-interface-designSkill
- go-openapiSkill
- go-project-layoutSkill
- go-code-reviewSkill
- go-coding-standardsSkill
- go-contextSkill
- go-data-structuresSkill
- go-documentationSkill
- go-error-handlingSkill
- go-modernizeSkill
- go-namingSkill
- go-databaseSkill
- go-concurrency-reviewSkill
- go-defensive-codingSkill
- go-observabilitySkill
- go-performance-reviewSkill
- go-security-auditSkill
- go-troubleshootingSkill
- go-test-table-drivenSkill
- git-commitSkill
- go-binary-sizeSkill
- go-build-releaseSkill
- go-ciSkill
- go-dependency-auditSkill
- go-refactoringSkill
- go-semantic-toolsSkill
- go-skills-routerSkill
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

