Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

go-unit-tests

БесплатноБез исполняемых скриптовНе проверен

Use for any question or task about Go tests, including quick how-to questions and one table-driven test: t.Run subtests, t.Parallel, helpers, data races that…

testlandот testland★ 18 звёзд на GitHub

Об этом скилле

go-unit-tests

Overview

Per pkg.go.dev/testing:

Go's testing package is stdlib - no separate install, no configuration file. The single binary go test discovers, builds, and runs tests via convention: _test.go suffix; TestXxx / BenchmarkXxx / FuzzXxx / ExampleXxx function-name prefixes. The table-driven idiom is built into the language style, and benchmarks + fuzzing (Go 1.18+) are native.

Choosing a framework

  1. stdlib testing is the idiomatic default - zero install, zero config, works wherever Go works.
  2. Ginkgo + Gomega when the project lives in the Kubernetes ecosystem (k8s.io/*, sigs.k8s.io/*, knative.dev/* in go.mod) or the team has an explicit BDD culture → references/ginkgo.md.
  3. Match the existing convention: Ginkgo in go.sum plus a *_suite_test.go bootstrap (or Describe/Context/It blocks in existing tests) → stay on Ginkgo; otherwise stdlib. Never switch frameworks mid-project.
  4. Mocking across interface boundaries → references/go-mocking.md (gomock codegen vs testify/mock hand-written stubs).

Step 1 - First test

// math_test.go
package math

import "testing"

func TestAdd(t *testing.T) {
    if got := Add(1, 2); got != 3 {
        t.Errorf("Add(1, 2) = %d; want 3", got)
    }
}
go test ./...           # all packages recursively
go test -v              # verbose
go test -run TestAdd    # specific test by name pattern

Step 2 - Table-driven tests (the Go idiom)

Per pkg.go.dev/testing#hdr-Subtests_and_Sub_benchmarks:

func TestAdd(t *testing.T) {
    tests := []struct {
        name           string
        a, b, expected int
    }{
        {"positive", 1, 2, 3},
        {"zero", 0, 0, 0},
        {"negative", -1, 1, 0},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := Add(tt.a, tt.b); got != tt.expected {
                t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, got, tt.expected)
            }
        })
    }
}

t.Run creates subtests with hierarchical names (TestAdd/positive), individually filterable via go test -run TestAdd/positive. A bare loop without t.Run reports every failure under the parent name only.

Step 3 - t.Parallel()

func TestSomethingSlow(t *testing.T) {
    t.Parallel()   // marks this test as parallel-safe
}

Parallel tests run concurrently with other parallel tests in the same package. In subtest loops pre-Go 1.22, capture the loop variable (tt := tt) or all subtests share the last iteration's value.

Step 4 - Benchmarks

func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Add(1, 2)
    }
}
go test -bench=. -benchmem                # with allocation tracking
go test -bench=. -count=10 > old.txt      # statistical comparison:
benchstat old.txt new.txt

Step 5 - Examples (executable docs)

func ExampleAdd() {
    fmt.Println(Add(1, 2))
    // Output: 3
}

The // Output: comment is the assertion; examples appear in go doc.

Step 6 - Native fuzzing (Go 1.18+)

Per pkg.go.dev/testing#hdr-Fuzzing:

func FuzzAdd(f *testing.F) {
    f.Add(1, 2)   // seed corpus
    f.Add(-1, 1)

    f.Fuzz(func(t *testing.T, a, b int) {
        c := Add(a, b)
        if c-a != b {
            t.Errorf("Add(%d, %d) = %d; expected invariant", a, b, c)
        }
    })
}
go test -fuzz=FuzzAdd -fuzztime=30s

Failures are cached at testdata/fuzz/FuzzAdd/; subsequent go test runs replay those cases as regression tests.

Step 7 - Coverage

go test -cover                                # summary
go test -coverprofile=coverage.out -coverpkg=./... ./...
go tool cover -html=coverage.out              # browser view
go tool cover -func=coverage.out              # per-function

No built-in threshold flag - gate via shell:

COVERAGE=$(go tool cover -func=coverage.out | grep total | awk '{print substr($3, 1, length($3)-1)}')
if (( $(echo "$COVERAGE < 80" | bc -l) )); then
    echo "Coverage $COVERAGE% below 80% threshold"; exit 1
fi

Step 8 - Build tags and helpers

//go:build integration

go test -tags=integration ./... runs per-environment suites without a separate folder structure.

func setupTest(t *testing.T) *Database {
    t.Helper()   // failure messages point to the caller
    db := openTestDB()
    t.Cleanup(func() { db.Close() })
    return db
}

Step 9 - CI integration

- run: go test -race -coverprofile=coverage.out -v ./...
- uses: codecov/codecov-action@v4
  with: { files: coverage.out }

-race enables the race detector - standard practice for any Go project with concurrency. JUnit XML for `junit-

Полный SKILL.md на GitHub

Установить go-unit-tests в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

.tessl-plugin/plugin.jsonreferences/ginkgo.mdreferences/go-mocking.md

FAQ

Что делает скилл go-unit-tests?

Use for any question or task about Go tests, including quick how-to questions and one table-driven test: t.Run subtests, t.Parallel, helpers, data races that fail in CI (go test -race), fuzz tests, benchmarks and coverage, plus testify, gomock and Ginkgo. Has Go test idioms, CI flags and anti-patterns.

Как установить скилл go-unit-tests?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл go-unit-tests запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить go-unit-tests с