ferroxlabs/wayland/go-testing-patterns

Claude Code and agent skill by ferroxlabs/wayland

Trust tier 2
  • community
  • ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
LLM review pending
Source check pending

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-patterns

Semi-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 testify library (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.mod configuration -- use go-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.Run subtests. 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 via init() or package-level globals.
  • HTTP handlers and middleware: Use net/http/httptest.NewRecorder() for handler-level tests and httptest.NewServer() for full integration roundtrips including middleware chains.
  • Database-touching code: Use a real test database (ephemeral Docker container via ory/dockertest or testcontainers-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/exec with a compiled binary in TestMain, or restructure the command logic to accept an io.Writer for output so it can be tested without subprocess overhead.
  • Concurrent or goroutine-based code: Always run with -race. Use channels or sync.WaitGroup to synchronize, never time.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 _test package (blackbox testing: package mypackage_test) to enforce API boundary discipline. Prefer _test suffix 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 of go test.
  • Use internal/testhelpers or a dedicated testutil package for shared helper functions. Export helpers from this package, not from production packages.
  • Never put test helpers in _test.go files if they need to be shared across packages -- _test.go files 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). Call os.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, and wantErr bool or a specific error type check.
  • Use t.Run(tc.name, func(t *testing.T) { ... }) for each case. This produces output like --- FAIL: TestParseURL/empty_host which 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 calling t.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 where wantErr: true and verify error content -- not just err != nil.
go
func TestParseAmount(t *testing.T) {
t.Parallel()
tests := []struct {
name string
input string
want int64
wantErr bool
}{
{name: "valid_integer", input: "100", want: 100},
{name: "leading_zeros", input: "007", want: 7},
{name: "empty_string", input: "", wantErr: true},
{name: "negative_value", input: "-5", wantErr: true},
{name: "overflow_int64", input: "99999999999999999999", wantErr: true},
}
for _, tc := range tests {
tc := tc // pre-1.22 capture fix
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
got, err := ParseAmount(tc.input)
if tc.wantErr {
if err == nil {
t.Fatalf("expected error, got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != tc.want {
t.Errorf("got %d, want %d", got, tc.want)
}
})
}
}
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 that err guards. require calls t.FailNow() which stops the current test immediately; assert calls t.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 calling m.Called(args...), and set up expectations with mockObj.On("MethodName", args).Return(values). Always call mockObj.AssertExpectations(t) at the end of each test that uses a mock.
  • Do NOT use testify/suite for new code. Suites add SetupTest/TeardownTest lifecycle hooks but obscure test structure, make parallelism awkward, and create hidden coupling between tests. Use explicit helper functions and t.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 with http.NewRequest("GET", "/path", nil), call handler.ServeHTTP(rec, req), then inspect rec.Code, rec.Body.String(), and rec.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. Call defer 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 with ts.Client() which is pre-configured to trust it.
  • When testing a router (e.g., chi, gorilla/mux, stdlib ServeMux), pass the fully assembled router to httptest.NewRecorder() or httptest.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.Request to 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.
go
func TestCreateUserHandler(t *testing.T) {
svc := &fakeUserService{createResult: &User{ID: "u1", Email: "a@b.com"}}
h := NewUserHandler(svc)
body := `{"email":"a@b.com","password":"secret123"}`
req := httptest.NewRequest(http.MethodPost, "/users", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
require.Equal(t, http.StatusCreated, rec.Code)
var resp UserResponse
require.NoError(t, json.NewDecoder(rec.Body).Decode(&resp))
assert.Equal(t, "u1", resp.ID)
assert.Equal(t, "a@b.com", resp.Email)
}
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

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
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/ferroxlabs/wayland/go-testing-patterns/badge)](https://verified-skill.com/skills/ferroxlabs/wayland/go-testing-patterns)

Something wrong with this skill or its page? Tell us.