关于
This skill provides comprehensive guidance on Go testing patterns for production-grade code, covering techniques like subtests, mocking, fixtures, and fuzz testing. Use it when writing or improving tests, setting up test infrastructure, or choosing testing approaches. It specifically excludes performance benchmarking, security testing, and table-driven test patterns which have dedicated skills.
快速安装
Claude Code
推荐npx skills add eduardo-sl/go-agent-skills -a claude-code/plugin add https://github.com/eduardo-sl/go-agent-skillsgit clone https://github.com/eduardo-sl/go-agent-skills.git ~/.claude/skills/go-test-quality在 Claude Code 中复制并粘贴此命令以安装该技能
技能文档
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.
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.
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 refactor
One 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) { ... }
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: "[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)
})
}
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 (os.Setenv).
go test -race -coverprofile=coverage.out ./...
go tool cover -func=coverage.out
Targets: business logic 80%+, critical paths (auth, payments) 95%+, handlers 70%+. Don't chase 100% on generated code and simple getters.
Anti-Patterns
- 🔴 Test with no assertions — always passes, proves nothing
- 🔴
time.Sleepfor synchronization — use 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
- 🟢 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
- Edge cases covered: empty, nil, zero, boundary values
go test -race ./...passes- Coverage is meaningful, not just high numbers
GitHub 仓库
常见问题
什么是 go-test-quality Skill?
go-test-quality 是一个 Claude Skill,作者为 eduardo-sl。Skill 将 Claude 按需加载的说明和资源打包,让 Claude 无需额外提示即可执行与 go-test-quality 相关的任务。
如何安装 go-test-quality?
使用本页的安装命令:将 go-test-quality 作为插件添加到 Claude Code,或将其仓库克隆到 skills 目录,然后重启 Claude 以加载该 Skill。
go-test-quality 属于哪个分类?
go-test-quality 属于测试分类。
go-test-quality 可以免费使用吗?
可以。go-test-quality 已收录在 AIMCP,可免费安装。
相关推荐技能
该Skill通过60+个学术基准测试(如MMLU、GSM8K等)评估大语言模型质量,适用于模型对比、学术研究及训练进度追踪。它支持HuggingFace、vLLM和API接口,被EleutherAI等行业领先机构广泛采用。开发者可通过简单命令行快速对模型进行多任务批量评估。
这个Claude Skill提供了关于Cloudflare Cron Triggers的完整知识库,用于通过cron表达式定时执行Workers。它支持配置周期性任务、维护作业和自动化工作流,并能处理常见的cron触发错误。开发者可以用它来设置定时任务、测试cron处理器,并集成Workflows和Green Compute功能。
该Skill为开发者提供了基于Playwright的本地Web应用测试工具集,支持自动化测试前端功能、调试UI行为、捕获屏幕截图和查看浏览器日志。它包含管理服务器生命周期的辅助脚本,可直接作为黑盒工具运行而无需阅读源码。适用于需要快速验证本地Web应用界面和交互功能的开发场景。
这个Skill用于开发分支完成后的集成决策,当代码实现完成且测试通过时,它会引导开发者选择合适的工作流。它首先验证测试状态,然后提供合并、创建PR或清理等结构化选项。核心价值在于确保代码质量的同时,标准化分支收尾流程。
