Back to Skills

golang-testing

verified

Go 测试模式,包括表格驱动测试、子测试、基准测试、模糊测试和测试覆盖率。遵循测试驱动开发(TDD)方法论及地道的 Go 语言实践。

View on GitHub

Marketplace

everything-claude-code

xu-xiang/everything-claude-code-zh

Plugin

everything-claude-code

workflow

Repository

xu-xiang/everything-claude-code-zh
25stars

skills/golang-testing/SKILL.md

Last Verified

February 5, 2026

Install Skill

Select agents to install to:

Scope:
npx add-skill https://github.com/xu-xiang/everything-claude-code-zh/blob/main/skills/golang-testing/SKILL.md -a claude-code --skill golang-testing

Installation paths:

Claude
.claude/skills/golang-testing/
Powered by add-skill CLI

Instructions

# Go 测试模式 (Go Testing Patterns)

遵循测试驱动开发(TDD)方法论,编写可靠且易于维护的 Go 测试模式指南。

## 激活场景 (When to Activate)

- 编写新的 Go 函数或方法时
- 为现有代码增加测试覆盖率时
- 为性能关键型代码创建基准测试时
- 为输入验证实现模糊测试时
- 在 Go 项目中遵循 TDD 工作流时

## Go 的测试驱动开发 (TDD) 工作流

### 红-绿-重构 (RED-GREEN-REFACTOR) 循环

```
红色 (RED)      → 先写一个失败的测试
绿色 (GREEN)    → 编写最少的代码使测试通过
重构 (REFACTOR) → 在保持测试通过的前提下优化代码
重复 (REPEAT)   → 继续处理下一个需求
```

### Go 中 TDD 的具体步骤

```go
// 第 1 步:定义接口/签名
// calculator.go
package calculator

func Add(a, b int) int {
    panic("not implemented") // 占位符
}

// 第 2 步:编写失败的测试 (RED)
// calculator_test.go
package calculator

import "testing"

func TestAdd(t *testing.T) {
    got := Add(2, 3)
    want := 5
    if got != want {
        t.Errorf("Add(2, 3) = %d; want %d", got, want)
    }
}

// 第 3 步:运行测试 - 验证失败 (FAIL)
// $ go test
// --- FAIL: TestAdd (0.00s)
// panic: not implemented

// 第 4 步:实现最简代码 (GREEN)
func Add(a, b int) int {
    return a + b
}

// 第 5 步:运行测试 - 验证通过 (PASS)
// $ go test
// PASS

// 第 6 步:根据需要进行重构,并验证测试依然通过
```

## 表格驱动测试 (Table-Driven Tests)

Go 测试的标准模式。允许用最少的代码实现全面的覆盖。

```go
func TestAdd(t *testing.T) {
    tests := []struct {
        name     string
        a, b     int
        expected int
    }{
        {"positive numbers", 2, 3, 5},
        {"negative numbers", -1, -2, -3},
        {"zero values", 0, 0, 0},
        {"mixed signs", -1, 1, 0},
        {"large numbers", 1000000, 2000000, 3000000},
    }

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

### 包含错误情况的表格驱动测试

```go
func TestParseConfig(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        want    *Config
        wantErr bool
    }{
        {
            name:  "valid config",
            input: `{"host": "localhost", "port": 8080}`,
            want:  &Con

Validation Details

Front Matter
Required Fields
Valid Name Format
Valid Description
Has Sections
Allowed Tools
Instruction Length:
11592 chars