golang-testing

작성자: samber

We need to translate the given text from English to Korean, preserving the name "golang-testing" if it appears. The text is a description of a skill for Go testing. The instruction says to translate only the text inside <text>, and not include the name unless it appears in the source text. The name "golang-testing" does not appear in the source text, so we don't include it. We must preserve product names, protocol names, URLs, numbers, technical terms. So terms like "table-driven tests", "testify suites", "mocks", "parallel tests", "fuzzing", "fixtures", "goroutine leak detection", "goleak", "snapshot testing", "code coverage", "integration tests", "idiomatic test naming", "Go test CI", "flaky/slow tests", "samber/cc-skills-golang@golang-stretchr-testify", "measurement methodology" should be kept as is or translated appropriately? The instruction says "preserve product names, protocol names, URLs, numbers,

npx skills add https://github.com/samber/cc-skills-golang --skill golang-testing

Persona: You are a Go engineer who treats tests as executable specifications. You write tests to constrain behavior, not to hit coverage targets.

Thinking mode: Use ultrathink for test strategy design and failure analysis. Shallow reasoning misses edge cases and produces brittle tests that pass today but break tomorrow.

Orchestration mode: Use ultracode for auditing a large test suite — orchestrate the three sub-agents described in Audit mode (unit quality and coverage gaps, integration isolation, goroutine/race issues) and merge their findings into one gap report.

Modes:

  • Write mode — generating new tests for existing or new code. Work sequentially through the code under test; use gotests to scaffold table-driven tests, then enrich with edge cases and error paths.
  • Review mode — reviewing a PR's test changes. Focus on the diff: check coverage of new behaviour, assertion quality, table-driven structure, and absence of flakiness patterns. Sequential.
  • Audit mode — auditing an existing test suite for gaps, flakiness, or bad patterns (order-dependent tests, missing t.Parallel(), implementation-detail coupling). Launch up to 3 parallel sub-agents split by concern: (1) unit test quality and coverage gaps, (2) integration test isolation and build tags, (3) goroutine leaks and race conditions.
  • Debug mode — a test is failing or flaky. Work sequentially: reproduce reliably, isolate the failing assertion, trace the root cause in production code or test setup.

Community default. A company skill that explicitly supersedes samber/cc-skills-golang@golang-testing skill takes precedence.

Dependencies:

  • gotests: go install github.com/cweill/gotests/gotests@latest

Go Testing Best Practices

This skill guides the creation of production-ready tests for Go applications. Follow these principles to write maintainable, fast, and reliable tests.

Best Practices Summary

  1. Table-driven tests MUST use named subtests -- every test case needs a name field passed to t.Run
  2. Integration tests MUST use build tags (//go:build integration) to separate from unit tests
  3. Tests MUST NOT depend on execution order -- each test MUST be independently runnable
  4. Independent tests SHOULD use t.Parallel() when possible
  5. NEVER test implementation details -- test observable behavior and public API contracts
  6. Packages with goroutines SHOULD use goleak.VerifyTestMain in TestMain to detect goroutine leaks
  7. Use testify as helpers, not a replacement for standard library
  8. Mock interfaces, not concrete types
  9. Keep unit tests fast (< 1ms), use build tags for integration tests
  10. Run tests with race detection in CI
  11. Include examples as executable documentation
  12. Test files MUST be named after the source file under test, not after the function or method being tested
  13. Test functions SHOULD appear in the same order as the functions/methods they test in the source file

Test Structure and Organization

File Conventions

// package_test.go - tests in same package (white-box, access unexported)
package mypackage

// mypackage_test.go - tests in test package (black-box, public API only)
package mypackage_test

Name the test file after the source file it tests, not after the function or method under test. Go's convention is one test file per source file (foo.go -> foo_test.go), because tools (go test, coverage reports, IDE "jump to test" navigation, gotests) and reviewers all resolve tests by source file, not by symbol. A source file usually declares several functions/methods; splitting its tests by symbol name scatters them across many files and breaks that file-to-file mapping.

// ✓ Good — one test file per source file
helloworld.go       -> helloworld_test.go   // contains TestHelloWorld, TestAbcd, TestXyz, ...

// ✗ Bad — test file named after the function/method instead of the source file
helloworld.go       -> abcd_test.go         // wrong: should be helloworld_test.go

Exception: very large source files MAY be split into multiple _test.go files by concern (e.g. foo_test.go + foo_edgecases_test.go), but each split file's name MUST still be derived from the source file name, never from an individual function name. Prefer keeping a single _test.go file per source file even when it grows large — splitting adds navigation overhead and is rarely worth it; reach for the exception only when a single file becomes genuinely unwieldy to browse or review.

Within a test file, order test functions to match the order their tested functions/methods appear in the source file. A reader (human or agent) scrolling foo.go alongside foo_test.go can then find the matching test by position instead of searching; drift between the two orderings compounds every time either file grows.

Naming Conventions

func TestAdd(t *testing.T) { ... }               // function test
func TestMyStruct_MyMethod(t *testing.T) { ... } // method test
func BenchmarkAdd(b *testing.B) { ... }          // benchmark
func ExampleAdd() { ... }                        // example
func FuzzAdd(f *testing.F) { ... }               // fuzz test

Table-Driven Tests

Table-driven tests are the idiomatic Go way to test multiple scenarios. Always name each test case.

func TestCalculatePrice(t *testing.T) {
    tests := []struct {
        name     string
        quantity int
        unitPrice float64
        expected  float64
    }{
        {
            name:      "single item",
            quantity:  1,
            unitPrice: 10.0,
            expected:  10.0,
        },
        {
            name:      "bulk discount - 100 items",
            quantity:  100,
            unitPrice: 10.0,
            expected:  900.0, // 10% discount
        },
        {
            name:      "zero quantity",
            quantity:  0,
            unitPrice: 10.0,
            expected:  0.0,
        },
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got := CalculatePrice(tt.quantity, tt.unitPrice)
            if got != tt.expected {
                t.Errorf("CalculatePrice(%d, %.2f) = %.2f, want %.2f",
                    tt.quantity, tt.unitPrice, got, tt.expected)
            }
        })
    }
}

Common Pitfall: Assert Scope Leaking into Subtests

Never create a testify assert/require instance in the parent test function and reuse it inside t.Run closures. assert.New(t) captures the exact *testing.T it was built with, so if that t belongs to the parent, every failure raised inside the subtest gets attributed to the parent test in go test output — the failing subtest itself still reports --- PASS, silently hiding which case broke. This happens whether or not the subtest calls t.Parallel().

// WRONG -- `is` is bound to the parent's t
func TestCalculatePrice(t *testing.T) {
    is := assert.New(t)
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            is.Equal(tt.expected, CalculatePrice(tt.quantity, tt.unitPrice)) // misattributed on failure
        })
    }
}

// RIGHT -- each subtest builds its own instance from its own t
func TestCalculatePrice(t *testing.T) {
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            is := assert.New(t)
            is.Equal(tt.expected, CalculatePrice(tt.quantity, tt.unitPrice))
        })
    }
}

Verify with a deliberately-broken case: if go test -v -run TestName shows --- FAIL: TestName but every --- PASS: TestName/subtest_name line still says PASS, the assert scope is leaking.

Unit Tests

Unit tests should be fast (< 1ms), isolated (no external dependencies), and deterministic.

Testing HTTP Handlers

Use httptest for handler tests with table-driven patterns. See HTTP Testing for examples with request/response bodies, query parameters, headers, and status code assertions.

Goroutine Leak Detection with goleak

Use go.uber.org/goleak to detect leaking goroutines, especially for concurrent code:

import (
    "testing"
    "go.uber.org/goleak"
)

func TestMain(m *testing.M) {
    goleak.VerifyTestMain(m)
}

To exclude specific goroutine stacks (for known leaks or library goroutines):

func TestMain(m *testing.M) {
    goleak.VerifyTestMain(m,
        goleak.IgnoreCurrent(),
    )
}

Or per-test:

func TestWorkerPool(t *testing.T) {
    defer goleak.VerifyNone(t)
    // ... test code ...
}

testing/synctest for Deterministic Goroutine Testing

testing/synctest (Go 1.25+) provides deterministic tests for goroutines, timers, deadlines, and context cancellation. Time advances only when all goroutines are blocked, making ordering predictable.

When to use synctest instead of real time:

  • Testing concurrent code with time-based operations (time.Sleep, time.After, time.Ticker)
  • When race conditions need to be reproducible
  • When tests are flaky due to timing issues
import (
    "context"
    "testing"
    "testing/synctest"
    "time"
)

func TestContextTimeout(t *testing.T) {
    synctest.Test(t, func(t *testing.T) {
        const timeout = 5 * time.Second

        ctx, cancel := context.WithTimeout(t.Context(), timeout)
        defer cancel()

        time.Sleep(timeout - time.Nanosecond)
        synctest.Wait()
        if err := ctx.Err(); err != nil {
            t.Fatalf("before timeout: %v", err)
        }

        time.Sleep(time.Nanosecond)
        synctest.Wait()
        if err := ctx.Err(); err != context.DeadlineExceeded {
            t.Fatalf("after timeout: got %v, want DeadlineExceeded", err)
        }
    })
}

Use synctest.Test in Go 1.25+ and Go 1.26+. Do not use the old Go 1.24 experimental synctest.Run API in Go 1.25+ or Go 1.26+ code. If a module explicitly targets Go 1.24 and opts into GOEXPERIMENT=synctest, use the old API only as a compatibility fallback.

Key differences in synctest:

  • time.Sleep advances synthetic time instantly when the goroutine blocks
  • time.After fires when synthetic time reaches the duration
  • All goroutines run to blocking points before time advances
  • Test execution is deterministic and repeatable

Test Timeouts

For tests that may hang, use a timeout helper that panics with caller location. See Helpers.

Benchmarks

→ See samber/cc-skills-golang@golang-benchmark skill for advanced benchmarking: b.Loop() (Go 1.24+), benchstat, profiling from benchmarks, and CI regression detection.

Write benchmarks to measure performance and detect regressions:

func BenchmarkStringConcatenation(b *testing.B) {
    b.Run("plus-operator", func(b *testing.B) {
        for b.Loop() {
            result := "a" + "b" + "c"
            _ = result
        }
    })

    b.Run("strings.Builder", func(b *testing.B) {
        for b.Loop() {
            var builder strings.Builder
            builder.WriteString("a")
            builder.WriteString("b")
            builder.WriteString("c")
            _ = builder.String()
        }
    })
}

Benchmarks with different input sizes:

func BenchmarkFibonacci(b *testing.B) {
    sizes := []int{10, 20, 30}
    for _, size := range sizes {
        b.Run(fmt.Sprintf("n=%d", size), func(b *testing.B) {
            b.ReportAllocs()
            for b.Loop() {
                Fibonacci(size)
            }
        })
    }
}

For Go 1.24+, new benchmarks should use b.Loop(). Use legacy b.N loops only when the module targets Go <1.24 or when preserving old benchmark code intentionally.

Go 1.26+: test artifacts

When a test, benchmark, or fuzz target needs to persist files for inspection, use ArtifactDir() instead of ad-hoc paths or repo-local output.

func TestRenderGoldenArtifact(t *testing.T) {
    dir := t.ArtifactDir()

    out := filepath.Join(dir, "rendered.json")
    if err := os.WriteFile(out, renderedBytes, 0o644); err != nil {
        t.Fatal(err)
    }

    t.Logf("artifact written: %s", out)
}

Available on *testing.T, *testing.B, and *testing.F in Go 1.26+.

Parallel Tests

Use t.Parallel() to run tests concurrently:

func TestParallelOperations(t *testing.T) {
    tests := []struct {
        name string
        data []byte
    }{
        {"small data", make([]byte, 1024)},
        {"medium data", make([]byte, 1024*1024)},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            t.Parallel()
            is := assert.New(t)

            result := Process(tt.data)
            is.NotNil(result)
        })
    }
}

Fuzzing

Use fuzzing to find edge cases and bugs:

func FuzzReverse(f *testing.F) {
    f.Add("hello")
    f.Add("")
    f.Add("a")

    f.Fuzz(func(t *testing.T, input string) {
        reversed := Reverse(input)
        doubleReversed := Reverse(reversed)
        if input != doubleReversed {
            t.Errorf("Reverse(Reverse(%q)) = %q, want %q", input, doubleReversed, input)
        }
    })
}

Examples as Documentation

Examples are executable documentation verified by go test:

func ExampleCalculatePrice() {
    price := CalculatePrice(100, 10.0)
    fmt.Printf("Price: %.2f\n", price)
    // Output: Price: 900.00
}

func ExampleCalculatePrice_singleItem() {
    price := CalculatePrice(1, 25.50)
    fmt.Printf("Price: %.2f\n", price)
    // Output: Price: 25.50
}

Code Coverage

# Generate coverage file
go test -coverprofile=coverage.out ./...

# View coverage in HTML
go tool cover -html=coverage.out

# Coverage by function
go tool cover -func=coverage.out

# Total coverage percentage
go tool cover -func=coverage.out | grep total

Integration Tests

Use build tags to separate integration tests from unit tests:

//go:build integration

package mypackage

func TestDatabaseIntegration(t *testing.T) {
    db, err := sql.Open("postgres", os.Getenv("DATABASE_URL"))
    if err != nil {
        t.Fatal(err)
    }
    defer db.Close()

    // Test real database operations
}

Run integration tests separately:

go test -tags=integration ./...

For Docker Compose fixtures, SQL schemas, and integration test suites, see Integration Testing.

Mocking

Mock interfaces, not concrete types. Define interfaces where consumed, then create mock implementations.

For mock patterns, test fixtures, and time mocking, see Mocking.

Enforce with Linters

Many test best practices are enforced automatically by linters: thelper, paralleltest, testifylint. See the samber/cc-skills-golang@golang-lint skill for configuration and usage.

Cross-References

  • -> See samber/cc-skills-golang@golang-stretchr-testify skill for detailed testify API (assert, require, mock, suite)
  • -> See samber/cc-skills-golang@golang-database skill (testing.md) for database integration test patterns
  • -> See samber/cc-skills-golang@golang-concurrency skill for goroutine leak detection with goleak
  • -> See samber/cc-skills-golang@golang-continuous-integration skill for CI test configuration and GitHub Actions workflows
  • -> See samber/cc-skills-golang@golang-lint skill for testifylint and paralleltest configuration
  • -> See samber/cc-skills-golang@golang-continuous-integration skill for automated AI-driven code review in CI using these guidelines

Quick Reference

go test ./...                          # all tests
go test -run TestName ./...            # specific test by exact name
go test -run TestName/subtest ./...    # subtests within a test
go test -run 'Test(Add|Sub)' ./...     # multiple tests (regexp OR)
go test -run 'Test[A-Z]' ./...         # tests starting with capital letter
go test -run 'TestUser.*' ./...        # tests matching prefix
go test -run '.*Validation.*' ./...    # tests containing substring
go test -run TestName/. ./...          # all subtests of TestName
go test -run '/(unit|integration)' ./... # filter by subtest name
go test -race ./...                    # race detection
go test -cover ./...                   # coverage summary
go test -bench=. -benchmem ./...       # benchmarks
go test -fuzz=FuzzName ./...           # fuzzing
go test -tags=integration ./...        # integration tests

samber의 다른 스킬

golang-code-style
samber
We need to translate the given text from English to Korean, preserving the specified name "golang-code-style" and other technical terms. The instruction says to translate only the text inside <text>, and not include the name unless it appears in the source text. The name "golang-code-style" appears in the source? Actually, the source text does not contain "golang-code-style" explicitly; it's the directory item name. The instruction says "Do not include the name unless it appears in the source text." So we should not add it. The source text has references to other skills like "samber/cc-skills-golang@golang-naming" etc. Those should be preserved as is. We need to translate the description of the skill. The text describes what the skill is about: Go code style conventions, line length, variable declarations, etc. And it says when to use it and what it's not for, with cross-references. We'll produce a natural Korean translation. Keep technical terms like "Go", "linter", "doc comments" as is
developmentcode-review
golang-design-patterns
samber
관용적인 Golang 디자인 패턴 — 함수형 옵션, 생성자, 오류 흐름 및 연쇄, 리소스 관리 및 생명주기, 정상 종료, 복원력, 아키텍처, 의존성 주입, 데이터 처리, 스트리밍 등. 아키텍처 패턴을 명시적으로 선택할 때, 함수형 옵션을 구현할 때, 생성자 API를 설계할 때, 정상 종료를 설정할 때, 복원력 패턴을 적용할 때, 또는 특정 문제에 맞는 관용적인 Go 패턴을 질문할 때 적용하세요.
developmentdesigncode-review
golang-error-handling
samber
관용적인 Golang 오류 처리 — 생성, %w를 사용한 래핑, errors.Is/As, errors.Join, 사용자 정의 오류 타입, 센티널 오류
developmentcode-review
golang-performance
samber
Golang 성능 최적화 패턴 및 방법론 - X 병목이 발생하면 Y를 적용. 할당 감소, CPU 효율성, 메모리 레이아웃, GC 튜닝, 풀링, 캐싱, 핫패스 최적화를 다룹니다. 프로파일링이나 벤치마크에서 병목이 확인되어 이를 해결할 적절한 최적화 패턴이 필요할 때 사용합니다. 또한 성능 코드 리뷰 시 개선 사항이나 빠른 성능 향상을 식별하는 데 도움이 될 벤치마크를 제안할 때 사용합니다. 측정 방법론에는 해당하지 않습니다(→...
developmentcode-review
golang-security
samber
Golang의 보안 모범 사례와 취약점 방지. 인젝션(SQL, 명령어, XSS), 암호화, 파일 시스템 안전, 네트워크 보안, 쿠키, 비밀 관리, 메모리 안전, 로깅을 다룹니다. 보안을 위해 Go 코드를 작성, 검토 또는 감사할 때, 또는 암호화, I/O, 비밀 관리, 사용자 입력 처리, 인증과 관련된 위험한 코드 작업 시 적용하세요. 보안 도구 구성도 포함됩니다.
securitycode-reviewdevelopment
golang-database
samber
Go 데이터베이스 접근에 대한 종합 가이드 — 매개변수화된 쿼리, 구조체 스캐닝, NULL 가능 컬럼, 트랜잭션, 격리 수준, SELECT FOR UPDATE, 연결 풀, 배치 처리, 컨텍스트 전파, 마이그레이션 도구. PostgreSQL, MariaDB, MySQL, SQLite와 상호작용하는 Golang 코드를 작성, 검토, 디버깅할 때 사용하거나, 데이터베이스 테스트 시, 또는 database/sql, sqlx, pgx에 대한 질문이 있을 때 사용합니다. 데이터베이스 스키마나 마이그레이션 SQL은 생성하지 않습니다.
developmentdatabase
golang-lint
samber
Golang 프로젝트를 위한 린팅 모범 사례와 golangci-lint 설정 — 린터 실행, .golangci.yml 구성, nolint 지시어로 경고 억제, 린트 출력 해석, 린터 선택. golangci-lint를 구성할 때, 린트 경고나 nolint 억제에 대해 질문할 때, 코드 품질 도구를 설정할 때, 또는 린터를 선택할 때 사용합니다. 또한 사용자가 golangci-lint, go vet, staticcheck, revive를 언급할 때 사용합니다.
developmentcode-reviewtesting
golang-troubleshooting
samber
Troubleshoot Golang programs systematically - find and fix the root cause. Use when encountering bugs, crashes, deadlocks, or unexpected behavior in Go code. Covers debugging methodology, common Go pitfalls, test-driven debugging, pprof setup and capture, Delve debugger, race detection, GODEBUG tracing, and production debugging. Start here for any 'something is wrong' situation. Not for interpreting profiles or benchmarking (→ See `samber/cc-skills-golang@golang-benchmark` skill) or applying...
developmenttesting