ferroxlabs/wayland/go-testing-patterns
Claude Code and agent skill by ferroxlabs/wayland
- community
- ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Checking that the SKILL.md file is still in the repository.
Guides expert-level Go testing: table-driven tests, testify assertions, httptest for HTTP handlers, integration test patterns, benchmarks, and fuzz testing. Use when the user asks about Go testing, table-driven tests, testify, httptest, benchmarks, fuzz testing, Go test organization. Do NOT use when the user asks about Go project setup (use `go-project-setup`), Go idioms (use `go-idioms`), general testing concepts (use `unit-testing-patterns`).
Install
npx vskill@latest install ferroxlabs/wayland/go-testing-patternsSemi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard
SKILL.md
The same SKILL.md was published earlier as ferroxlabs/wayland/go-testing-patterns.
Go Testing Patterns
When to Use
Use this skill when:
- The user asks how to structure test files, test functions, or test packages in a Go project
- The user asks about table-driven tests, subtests, or parameterized testing in Go
- The user asks about the
testifylibrary (assert,require,mock,suite) or whether to use it over stdlib - The user asks about testing HTTP handlers or middleware using
net/http/httptest - The user asks about writing benchmarks with
testing.B, profiling benchmarks, or avoiding benchmark optimizations that skew results - The user asks about fuzz testing with
testing.F(Go 1.18+), seed corpus, or fuzz targets - The user asks about integration tests, test helpers,
TestMain, or golden files in Go - The user asks about race condition detection, parallel tests, or coverage thresholds in Go CI
Do NOT use this skill when:
- The user asks about initializing a Go module, project layout, or
go.modconfiguration -- usego-project-setup - The user asks about Go idioms, error handling conventions, or interface design -- use
go-idioms - The user asks about general unit testing theory, TDD philosophy, or test pyramid concepts without Go specifics -- use
unit-testing-patterns - The user asks about Go concurrency patterns without a testing focus -- use
go-concurrency - The user asks about CI/CD pipeline configuration that happens to run Go tests -- use
ci-cd-pipelines - The user asks about load testing or performance profiling in production -- use
performance-profiling
Process
1. Identify the Test Category and Appropriate Pattern
Classify what is being tested before writing a single line of test code. Each category has a canonical Go approach.
- Pure functions with no side effects: Standard table-driven tests using
t.Runsubtests. No mocking required. Focus on boundary values, zero values, and error paths. - Methods on structs with injected dependencies: Interface-based fakes or
testify/mock. Inject via constructor, never viainit()or package-level globals. - HTTP handlers and middleware: Use
net/http/httptest.NewRecorder()for handler-level tests andhttptest.NewServer()for full integration roundtrips including middleware chains. - Database-touching code: Use a real test database (ephemeral Docker container via
ory/dockertestortestcontainers-go) or a recorded query replay tool. Never use SQLite as a substitute for Postgres -- schema differences cause false confidence. - File system or OS interaction: Use
t.TempDir()(Go 1.15+) which automatically cleans up after the test. Never hardcode/tmp/paths. - CLI commands: Use
os/execwith a compiled binary inTestMain, or restructure the command logic to accept anio.Writerfor output so it can be tested without subprocess overhead. - Concurrent or goroutine-based code: Always run with
-race. Use channels orsync.WaitGroupto synchronize, nevertime.Sleep.
2. Set Up the Test File Structure
Go test files have strict conventions that must be respected.
- Place test files in the same package as the code under test (whitebox testing:
package mypackage) to access unexported identifiers, OR in a_testpackage (blackbox testing:package mypackage_test) to enforce API boundary discipline. Prefer_testsuffix packages for exported APIs; use internal packages for unexported logic testing. - Name the test file
{filename}_test.go. Go tooling will not compile these files outside ofgo test. - Use
internal/testhelpersor a dedicatedtestutilpackage for shared helper functions. Export helpers from this package, not from production packages. - Never put test helpers in
_test.gofiles if they need to be shared across packages --_test.gofiles are not importable by other packages. - Place integration tests in a separate
integration/directory or gate them behind a build tag://go:build integration. Run them separately in CI:go test -tags=integration ./.... - Use
TestMain(m *testing.M)only when you need true global setup/teardown (starting a database container, compiling a binary, seeding shared fixtures). Callos.Exit(m.Run())at the end -- failing to do so causes the test binary to report success regardless of test outcomes.
3. Write Table-Driven Tests with Subtests
Table-driven tests are idiomatic Go. Apply this pattern consistently for any function that processes varied inputs.
- Define a slice of anonymous structs (not a map -- maps have non-deterministic iteration order) containing:
name string, input fields, expected output fields, andwantErr boolor a specific error type check. - Use
t.Run(tc.name, func(t *testing.T) { ... })for each case. This produces output like--- FAIL: TestParseURL/empty_hostwhich is grep-friendly. - Mark subtests as parallel with
tt := tc; t.Parallel()inside the subtest closure. Assign the loop variable to a local copy (tt) before callingt.Parallel()-- failing to do so is the classic Go loop variable capture bug that was fixed only in Go 1.22. For Go < 1.22, this copy is mandatory. - Name test cases with snake_case or short descriptive phrases:
"empty_input","max_int_boundary","unicode_multibyte_sequence". Avoid"test 1","case A", or numeric-only names. - Group cases that test error conditions at the end of the table. Arrange happy-path cases first for readability.
- For functions returning
error, always include at least one case wherewantErr: trueand verify error content -- not justerr != nil.
4. Choose Between stdlib Assertions and testify
The stdlib provides t.Error, t.Errorf, t.Fatal, and t.Fatalf. Testify provides assert and require packages. Make a deliberate choice per project and stick to it.
- Use stdlib only when the project has zero external test dependencies, when assertions are simple equality or nil checks, and when the team is comfortable with verbose error messages.
- Use `testify/assert` when you need rich diff output for struct comparisons, when you want to continue running the rest of a test after a failure (non-fatal assertions), or when testing teams find the
assert.Equal(t, expected, actual)signature more readable. - Use `testify/require` (same API as
assert) when a failure means the test cannot meaningfully continue -- e.g.,require.NoError(t, err)before using a value thaterrguards.requirecallst.FailNow()which stops the current test immediately;assertcallst.Fail()which marks failure but continues execution. - The argument order convention for testify is
(t, expected, actual)-- putting expected first matches the error message format "expected X, got Y". Getting this backwards is a common mistake that produces confusing failure messages. - Use `testify/mock` for interface mocking. Define a struct that embeds
mock.Mock, implement the interface methods callingm.Called(args...), and set up expectations withmockObj.On("MethodName", args).Return(values). Always callmockObj.AssertExpectations(t)at the end of each test that uses a mock. - Do NOT use
testify/suitefor new code. Suites addSetupTest/TeardownTestlifecycle hooks but obscure test structure, make parallelism awkward, and create hidden coupling between tests. Use explicit helper functions andt.Cleanup()instead.
5. Test HTTP Handlers with httptest
The net/http/httptest package is the canonical tool for testing Go HTTP code without a real server.
- Use
httptest.NewRecorder()for testing a single handler function. Create the recorder, create a request withhttp.NewRequest("GET", "/path", nil), callhandler.ServeHTTP(rec, req), then inspectrec.Code,rec.Body.String(), andrec.Header(). - Use
httptest.NewServer(handler)to spin up a real TCP listener on a random port. This is required when testing middleware chains, redirect behavior, connection-level behavior, or client code that needs a real URL. Calldefer ts.Close()immediately after creating the server. - Use
httptest.NewTLSServer(handler)when testing TLS-specific behavior. The returned server uses a self-signed certificate; access it withts.Client()which is pre-configured to trust it. - When testing a router (e.g.,
chi,gorilla/mux,stdlib ServeMux), pass the fully assembled router tohttptest.NewRecorder()orhttptest.NewServer(). Do not test routes in isolation from the router -- the routing is part of the contract. - Set request headers explicitly:
req.Header.Set("Content-Type", "application/json"). Missing content-type headers cause handler failures that are not obvious from the test output. - For authenticated endpoints, add an auth header or cookie to the request in the test. Create a test helper
func newAuthRequest(t *testing.T, method, path string) *http.Requestto avoid repetition. - Parse and validate response bodies with
json.NewDecoder(rec.Body).Decode(&result)-- do not use string matching on JSON unless testing exact serialization format.
6. Write Benchmarks Correctly
Benchmarks in Go use testing.B and are invoked with go test -bench=. -benchmem. Common mistakes produce meaningless results.
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 96 of 100Pattern checks on the skill's files.
- Model reviewNot runA model review is scheduled for the next rescan.
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingsrc/process/resources/skills-library/bodies/skills/software-engineering/go-testing-patterns/SKILL.md
Popularity
- Repository stars
- 146
- Repository forks
- 32
- 7-day trend score
- 25
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Extension points
hookPre/post lifecycle hooks
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/ferroxlabs/wayland/go-testing-patterns)