Skills DirectorySkills Directory
SkillsLearnSecurityCategoriesDocsBlogPro
Sign InSubmit Skill
Skills Directory

Security-tested agent skills for Claude, coding agents, and AI workflows.

Directory

  • Browse Skills
  • All Skills A–Z
  • Claude Skills
  • Claude Code Skills
  • Agent Skills
  • Categories
  • Authors
  • Submit a Skill

Learn

  • Learn Hub
  • Install Claude Skills
  • Write SKILL.md
  • Skills vs MCP
  • Directories Compared

Security

  • Security
  • Methodology
  • Secure Claude Skills
  • Security Badges
  • Chrome Extension
  • Skill Manager

Company

  • About
  • Community
  • Blog
  • API Docs
  • Advertise

2026 Skills Directory. All rights reserved.

ProTermsPrivacyRefunds
Back to skills

Go Tests

ASecurity

Enforces idiomatic Go testing — table-driven cases with subtests, the standard library over assertion frameworks, t.Cleanup for teardown, httptest for HTTP, golden files, fuzzing, and benchmarks that measure. Use when writing or reviewing Go tests, and when the user mentions table tests, t.Run, t.Parallel, testify, testdata, golden files, httptest, go test -race, coverage, benchmarks, fuzz, or asks "how do I test this in Go".

2 stars
0 votes
0 copies
1 views
Added 9/19/2026
developmentrustgotestinggitapi

Works with

api

Security Analysis

A100/100

Scanned 9/19/2026

$npx -y skills add CasLubbers/code-design-skills --skill go-tests --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Go Tests?

Add the live security badge to your README — it updates automatically with every re-scan.

Security grade badge for Go Tests
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/caslubbers-go-tests/badge)](https://www.skillsdirectory.com/skills/caslubbers-go-tests)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
Files
SKILL.md
---
name: go-tests
description: Enforces idiomatic Go testing — table-driven cases with subtests, the standard library over assertion frameworks, t.Cleanup for teardown, httptest for HTTP, golden files, fuzzing, and benchmarks that measure. Use when writing or reviewing Go tests, and when the user mentions table tests, t.Run, t.Parallel, testify, testdata, golden files, httptest, go test -race, coverage, benchmarks, fuzz, or asks "how do I test this in Go".
---

# Go tests

## Table-driven is the default

One test function, a slice of cases, a subtest per case. Adding coverage means adding a struct literal.

```go
func TestParseDuration(t *testing.T) {
    tests := map[string]struct {
        in      string
        want    time.Duration
        wantErr bool
    }{
        "seconds":      {in: "30s", want: 30 * time.Second},
        "compound":     {in: "1h30m", want: 90 * time.Minute},
        "zero":         {in: "0", want: 0},
        "empty":        {in: "", wantErr: true},
        "bad unit":     {in: "5x", wantErr: true},
    }

    for name, tc := range tests {
        t.Run(name, func(t *testing.T) {
            t.Parallel()
            got, err := ParseDuration(tc.in)
            if tc.wantErr {
                if err == nil { t.Fatal("want error, got nil") }
                return
            }
            if err != nil { t.Fatalf("unexpected error: %v", err) }
            if got != tc.want { t.Errorf("got %v, want %v", got, tc.want) }
        })
    }
}
```

A map keys cases by name and randomises order, which surfaces inter-case dependencies. Name cases after the behaviour, not `case1`. `t.Run` gives each one its own line in the output and lets you run one with `-run TestParseDuration/bad_unit`.

## Failure messages carry the values

The reader is looking at CI output, not your screen.

```go
// Good
t.Errorf("ParseDuration(%q) = %v, want %v", tc.in, got, tc.want)

// Bad — tells you nothing
t.Error("wrong result")
```

`t.Error` continues so you see every failure in the table; `t.Fatal` stops when continuing would panic or cascade. Use `cmp.Diff` from `github.com/google/go-cmp` for structs and slices — comparing large values by eye is wasted time:

```go
if diff := cmp.Diff(want, got); diff != "" {
    t.Errorf("mismatch (-want +got):\n%s", diff)
}
```

## Standard library first

`testing` plus `go-cmp` covers nearly everything. An assertion framework buys `assert.Equal` and costs a dependency, a second vocabulary, and worse failure output for composite types. If a project already uses `testify`, match it — consistency wins over relitigating the choice.

## Cleanup with t.Cleanup

Registers teardown next to setup, runs even when the test fails, and works inside helpers where `defer` would fire too early.

```go
func newTestStore(t *testing.T) *Store {
    t.Helper()
    dir := t.TempDir()          // removed automatically
    s, err := Open(dir)
    if err != nil { t.Fatalf("open store: %v", err) }
    t.Cleanup(func() { s.Close() })
    return s
}
```

`t.Helper()` makes failures report the caller's line, not the helper's. `t.TempDir` and `t.Setenv` handle their own cleanup — `t.Setenv` also blocks `t.Parallel`, by design.

## Parallel tests

`t.Parallel()` is a signal that the test shares no mutable state — no global config, no fixed port, no shared temp file. Add it deliberately, and run with `-race`, which is where parallelism pays off by exposing real races.

## HTTP with httptest

No real ports, no sleeps.

```go
func TestHandler(t *testing.T) {
    req := httptest.NewRequest(http.MethodGet, "/orders/42", nil)
    rec := httptest.NewRecorder()

    NewHandler(fakeStore{}).ServeHTTP(rec, req)

    if rec.Code != http.StatusOK {
        t.Fatalf("status = %d, want 200", rec.Code)
    }
}
```

For outbound calls, `httptest.NewServer` gives a real URL backed by your own handler.

## Golden files

For large output — rendered templates, generated code, formatted reports — store the expected value in `testdata/` and regenerate behind a flag.

```go
var update = flag.Bool("update", false, "update golden files")

golden := filepath.Join("testdata", name+".golden")
if *update {
    os.WriteFile(golden, got, 0o644)
}
want, err := os.ReadFile(golden)
```

`testdata/` is ignored by the go tool, so anything can live there. Review golden diffs like code — a regenerated golden that nobody read is a test that asserts nothing.

## Test the exported surface

Prefer package `foo_test` (an external test package) so tests exercise the API a caller sees. Drop into the internal package only for logic genuinely unreachable from outside — and consider whether that logic wants extracting instead.

## Fuzzing and benchmarks

Fuzz anything that parses untrusted input; the corpus lives in `testdata/fuzz` and grows with every crash found.

```go
func FuzzParse(f *testing.F) {
    f.Add("30s")
    f.Fuzz(func(t *testing.T, s string) {
        _, _ = ParseDuration(s) // must not panic
    })
}
```

Benchmarks loop to `b.N` and must not be optimised away — assign to a package-level sink. Use `b.ReportAllocs()`, and compare runs with `benchstat` rather than eyeballing one number.

## What CI runs

```
go test -race -count=1 ./...
```

`-count=1` defeats the test cache when you need a true rerun. Coverage is a map of untested code, not a target — chasing a percentage produces tests that assert nothing.

Attribution

CasLubbersCasLubbers
View sourceSee grades on GitHubMore from CasLubbers →
SSkills Directory ProSkills Directory

Get any skill into Claude in one click.

Download any skill as a ZIP for Claude.ai, Claude Desktop, or .claude/skills. $9/mo.

See Pro

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments (0)

No comments yet. Be the first to comment!

SSkills Directory ProSkills Directory

Get any skill into Claude in one click.

Download any skill as a ZIP for Claude.ai, Claude Desktop, or .claude/skills. $9/mo.

See Pro

Related Skills

Clean Code

Pragmatic coding standards - concise, direct, no over-engineering, no unnecessary comments

304955 votes

Browser Extension Developer

Use this skill when developing or maintaining browser extension code in the `browser/` directory, including Chrome/Firefox/Edge compatibility, content scripts, background scripts, or i18n updates.

285172 votes

Seo Optimizer

SEO optimization with keyword analysis, readability assessment, technical validation, content quality. Use for search rankings, blog posts, content audits, or encountering keyword density, readability scores, meta tags, schema markup errors.

2222 votes

Google Official Seo Guide

Official Google SEO guide covering search optimization, best practices, Search Console, crawling, indexing, and improving website search visibility based on official Google documentation

1862 votes

Tanstack Start

Build a full-stack TanStack Start app on Cloudflare Workers from scratch — SSR, file-based routing, server functions, D1+Drizzle, better-auth, Tailwind v4+shadcn/ui. Use whenever the user mentions TanStack Start, asks to scaffold a full-stack Cloudflare app with SSR, wants an SSR dashboard, or asks for a React 19 + Cloudflare Workers app with file-based routing and server functions — even if they don't name TanStack Start specifically. No template repo — Claude generates every file fresh per ...

10311 votes
View all in development →