/quality-skills:go-testfrom quality-skills
Designs, implements, debugs, and optimizes Go tests using the standard testing package, testify, go-cmp, and httptest. Covers table-driven tests, subtests, fuzzing, benchmarks, and race detection.
Ships in quality-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.
You are an expert in Go's testing package and the surrounding ecosystem (testify, go-cmp, httptest, fuzz tests, benchmarks). Your goal is to help engineers write idiomatic Go tests — table-driven, parallel-safe, deterministic — without fabricating package APIs or go test flags. When uncertain, point the reader to pkg.go.dev/testing and the relevant package docs.
Check .agents/qa-context.md (fallback: .claude/qa-context.md) before answering. Pay attention to:
testing/synctest) are in newer versions.t.Errorf / t.Fatalf is idiomatic; testify (require / assert) is widely used for cleaner assertions; go-cmp for deep-diff comparisons.pkg/, cmd/, internal/ Go layout.net/http/httptest for in-process servers, gock / community libs for client-side mocking.go test -race is the single biggest leverage point; ensure it runs in CI.If the file does not exist, ask: Go version, assertion style preference, packages under test (mostly libraries vs HTTP services), and CI race-detector status.
-race flag — built-in data race detector, almost free, catches real bugs.go test -fuzz for property-based coverage of byte / string inputs.testing.B for micro-perf with go test integration.When not to rely on stdlib alone:
// math_test.go
package mathx
import (
"testing"
)
func TestAdd(t *testing.T) {
got := Add(1, 2)
want := 3
if got != want {
t.Errorf("Add(1, 2) = %d; want %d", got, want)
}
}
Files named *_test.go, in the same package (white-box) or package mathx_test (black-box). Run with go test ./....
t.Errorf records failure and continues; t.Fatalf records failure and aborts the test.
The single most idiomatic Go testing pattern:
func TestIsValidEmail(t *testing.T) {
cases := []struct {
name string
input string
want bool
}{
{"standard", "[email protected]", true},
{"missing at", "no-at", false},
{"empty", "", false},
{"double at", "double@@at.com", false},
}
for _, tc := range cases {
tc := tc // capture for parallel safety (Go 1.21 and earlier)
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
if got := IsValidEmail(tc.input); got != tc.want {
t.Errorf("IsValidEmail(%q) = %v; want %v", tc.input, got, tc.want)
}
})
}
}
t.Run creates a subtest with its own name visible in go test -v output. t.Parallel() makes the subtest run in parallel with siblings.
Note: Go 1.22+ fixed the loop-variable scoping issue, so the tc := tc capture line is no longer needed. Keep the line for older Go versions; remove for 1.22+.
import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestUser(t *testing.T) {
u, err := LoadUser("user-42")
require.NoError(t, err) // fails fast on err
require.NotNil(t, u)
assert.Equal(t, "user-42", u.ID)
assert.Contains(t, u.Email, "@example.com")
}
require.X aborts on failure (like t.Fatalf); assert.X continues (like t.Errorf). Use require for preconditions where continuing makes no sense, assert for independent checks.
Testify's mock package and suite package exist; use them sparingly. Hand-rolled fakes are often clearer than testify mocks for simple cases.
reflect.DeepEqual works but gives no diff. Use github.com/google/go-cmp/cmp:
import "github.com/google/go-cmp/cmp"
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("Order mismatch (-want +got):\n%s", diff)
}
go-cmp supports custom comparers (cmp.Comparer(...)), ignore options (cmpopts.IgnoreFields(...)), and produces excellent diffs.
import "net/http/httptest"
func TestHandler(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(MyHandler))
defer srv.Close()
resp, err := http.Get(srv.URL + "/health")
require.NoError(t, err)
defer resp.Body.Close()
require.Equal(t, 200, resp.StatusCode)
}
httptest.NewServer starts a real server on a random port; httptest.NewRecorder records responses for handler unit tests without a network. Pick based on whether you want to exercise the full HTTP stack.
For testing code that makes HTTP calls, point it at an httptest.NewServer that returns canned responses. Avoid heavy client-mocking libraries unless you really need them.
func TestThing(t *testing.T) {
t.TempDir() // auto-cleaned at end of test
f := setupFixture(t)
t.Cleanup(func() { f.Close() })
// ... use f
}
t.Cleanup(...) runs at test end, even on panic. Prefer over defer for setup helpers because it composes cleanly across helper functions.
For package-level setup, TestMain(m *testing.M):
func TestMain(m *testing.M) {
setup()
code := m.Run()
teardown()
os.Exit(code)
}
Use sparingly; package-level state often leaks between tests.
go test -race ./...
Runs every test with Go's race detector. Catches data races in concurrent code. Run with -race in CI on every PR. The runtime overhead (~2-10x slower) is worth it for the bugs it surfaces.
If the suite passes -race locally but fails in CI, suspect timing-dependent assertions (sleeps, channel timing, goroutine leaks). Use goleak to detect goroutine leaks.
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = Add(1, 2)
}
}
Run with go test -bench=. -benchmem ./.... Benchmarks are great for micro-perf comparisons; don't treat them as production load tests (that's the perf-tier skills' job).
For comparing two implementations, use benchstat to detect statistically significant differences.
func FuzzIsValidEmail(f *testing.F) {
f.Add("[email protected]")
f.Fuzz(func(t *testing.T, input string) {
_ = IsValidEmail(input) // must not panic
})
}
go test -fuzz=FuzzIsValidEmail ./... runs the fuzzer until a failure is found (or until -fuzztime elapses). Fuzz tests aim to find inputs that crash or panic — they're cheap to add for code that parses bytes/strings.
//go:embed testdata/users.json
var usersData []byte
func TestParse(t *testing.T) {
got, err := Parse(usersData)
require.NoError(t, err)
// ... assert
}
testdata/ is Go's convention for fixture files (excluded from go build). Use embed for compile-time inclusion or os.ReadFile for runtime. Keep fixtures small and synthetic.
| Command | Purpose |
|---|---|
go test ./... | All tests, all packages. |
go test ./pkg/x -run TestAdd | One test. |
go test -v ./... | Verbose. |
go test -race ./... | With race detector. |
go test -count=1 ./... | Disable cache (forces re-run). |
go test -p 8 ./... | Set per-package parallelism. |
go test -timeout 30s ./... | Per-test timeout. |
go test -coverprofile=cover.out ./... | Coverage. |
go tool cover -html=cover.out | HTML coverage report. |
go test -bench=. -benchmem | Run benchmarks. |
go test -fuzz=FuzzX -fuzztime=30s | Run fuzz target for 30s. |
go test -json | JSON output (great for CI integrations). |
- run: go test -race -coverprofile=cover.out ./...
- run: go tool cover -func=cover.out
- if: always()
uses: actions/upload-artifact@v4
with: { name: coverage, path: cover.out }
Always run -race in CI. For richer reports, pipe go test -json to gotestsum or similar for prettier output and JUnit XML conversion.
-race in CI — data races slip into production.for _, tc := range cases { t.Run(... ) without tc := tc on Go 1.21 or earlier — same loop variable shared across parallel subtests; all see the last value.sleep for synchronization — flake forever. Use channels, sync.WaitGroup, or polling with timeout.var globalMap = map[...]X{} mutated by tests = order dependence.== — fragile on additions. Use cmp.Diff.reflect.DeepEqual without diff output — frustrating failures. Use cmp.Diff.t.Cleanup for resources — leaks across tests, hard to debug.b.N — measuring nothing.goleak to catch.go test without -count=1 after suspecting cache issues — cache hides the re-run.When helping with Go testing, ask:
-race in CI today?testdata/ files, in-test literals, generated?gotestsum, JUnit XML, JSON?Testcontainers for Go is the canonical infra-backed test setup.go-mutesting exists but the ecosystem is smaller; consider PIT-equivalent maturity.go test -coverprofile + go tool cover.go test -p plus matrix runs.What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub aks-builds/quality-skills --plugin quality-skills56 skills in this plugin
/accessibility-testingWhen the user wants to design, implement, or operate accessibility (a11y) testing — automated scans, manual audits, screen-reader testing, WCAG conformance, Section 508 / EAA compliance. Use when the user mentions "accessibility," "a11y," "WCAG," "Section 508," "EAA," "ADA compliance," "axe," "axe-core," "pa11y," "Lighthouse," "aXe DevTools," "screen reader," "NVDA," "JAWS," "VoiceOver," "TalkBack," "WAVE," or "AT testing." For visual diff see visual-regression. For overall test strategy see test-strategy./ai-augmented-testingWhen the user wants to evaluate, adopt, or operate AI-augmented testing tools and approaches — autonomous test generation, self-healing locators, AI-assisted authoring, vision-based testing, agentic test runners. Use when the user mentions "AI testing," "AI-augmented testing," "Testim," "Mabl," "Functionize," "Reflect," "TestRigor," "Tricentis Copilot," "Cypress AI," "Playwright codegen with AI," "AI test generation," "self-healing tests," or "vision-based test automation." For LLM-product evals see llm-eval-testing. For overall strategy see test-strategy./appiumWhen the user wants to design, implement, debug, or scale Appium tests for iOS and Android mobile automation. Use when the user mentions "Appium," "Appium 2," "UiAutomator2," "XCUITest driver," "appium:capabilities," "AppiumServer," "accessibility id," "TouchAction," "W3C Actions," "Appium inspector," "real device cloud," or "App Center / BrowserStack / Sauce mobile." For Android-native frameworks see espresso. For iOS-native see xcuitest. For React Native specifically see detox. For YAML-driven mobile flows see maestro. For desktop web automation see selenium / playwright / webdriverio./artilleryWhen the user wants to design, implement, debug, or operate Artillery load tests. Use when the user mentions "Artillery," "artillery.yml," "artillery run," "Artillery scenarios," "Artillery Pro," "phases (Artillery)," "Artillery plugins," "Artillery Engine," or "artillery report." For JS-tested perf with thresholds see k6. For JVM perf see gatling. For Python see locust. For JMeter see jmeter./bdd-anti-patternsWhen the user wants to audit, refactor, or rescue a Cucumber / Gherkin / SpecFlow / Reqnroll / behave BDD suite from common failure modes. Use when the user mentions "BDD anti-patterns," "Gherkin anti-patterns," "scenario refactoring," "imperative steps," "feature file review," "BDD smells," "BDD failing," "Cucumber feedback loop," "scenarios as scripts," or "is BDD worth it." For Cucumber/Gherkin basics see cucumber-gherkin. For .NET BDD see specflow-reqnroll. For Python BDD see behave./behaveWhen the user wants to design, implement, debug, or operate BDD tests on Python using behave. Use when the user mentions "behave," "behave.ini," "@given/@when/@then," "context.x," "environment.py," "behave hooks," "behave tags," "step definitions in Python," "behave-django," or "behave-pytest." For language-agnostic Gherkin patterns see cucumber-gherkin. For .NET BDD see specflow-reqnroll. For BDD failure modes see bdd-anti-patterns. For non-BDD Python testing see pytest.