Skip to content
Development
Skill

/golang-testing

Go 测试模式,包括表格驱动测试、子测试、基准测试、模糊测试和测试覆盖率。遵循具有惯用 Go 实践的 TDD 方法论。

From plugin
everything-claude-code
1.8k59 skills15 agents35 commands6 hooks
Install
$ npx -y skills add xu-xiang/everything-claude-code-zh --skill golang-testing --agent claude-code

How it fires

How this skill gets triggered: by you, by Claude, or both.

  • Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
  • You can call itInvoke it directly when you want it.
  • Slash command/golang-testing

Context preview

The summary Claude sees to decide when to auto-load this skill.

Go 测试模式,包括表格驱动测试、子测试、基准测试、模糊测试和测试覆盖率。遵循具有惯用 Go 实践的 TDD 方法论。

SKILL.md

golang-testing.SKILL.md
name: golang-testing
description: Go 测试模式,包括表格驱动测试、子测试、基准测试、模糊测试和测试覆盖率。遵循具有惯用 Go 实践的 TDD 方法论。
origin: ECC

Go 测试模式 (Testing Patterns)

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

何时激活

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

Go 的 TDD 工作流

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

RED      → 先编写一个失败的测试
GREEN    → 编写最少的代码使测试通过
REFACTOR → 在保持测试通过的同时改进代码
REPEAT   → 继续处理下一个需求

Go 中的分步 TDD

// 步骤 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 测试的标准模式。能够以最少的代码实现全面的覆盖。

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)
            }
        })
    }
}

带错误情况的表格驱动测试

func TestParseConfig(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        want    *Config
        wantErr bool
    }{
        {
            name:  "valid config",
            input: `{"host": "localhost", "port": 8080}`,
            want:  &Config{Host: "localhost", Port: 8080},
        },
        {
            name:    "invalid JSON",
            input:   `{invalid}`,
            wantErr: true,
        },
        {
            name:    "empty input",
            input:   "",
            wantErr: true,
        },
        {
            name:  "minimal config",
            input: `{}`,
            want:  &Config{}, // 零值配置
        },
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := ParseConfig(tt.input)

            if tt.wantErr {
                if err == nil {
                    t.Error("expected error, got nil")
                }
                return
            }

            if err != nil {
                t.Fatalf("unexpected error: %v", err)
            }

            if !reflect.DeepEqual(got, tt.want) {
                t.Errorf("got %+v; want %+v", got, tt.want)
            }
        })
    }
}

子测试与子基准测试 (Subtests and Sub-benchmarks)

组织相关测试

func TestUser(t *testing.T) {
    // 所有子测试共享的设置
    db := setupTestDB(t)

    t.Run("Create", func(t *testing.T) {
        user := &User{Name: "Alice"}
        err := db.CreateUser(user)
        if err != nil {
            t.Fatalf("CreateUser failed: %v", err)
        }
        if user.ID == "" {
            t.Error("expected user ID to be set")
        }
    })

    t.Run("Get", func(t *testing.T) {
        user, err := db.GetUser("alice-id")
        if err != nil {
            t.Fatalf("GetUser failed: %v", err)
        }
        if user.Name != "Alice" {
            t.Errorf("got name %q; want %q", user.Name, "Alice")
        }
    })

    t.Run("Update", func(t *testing.T) {
        // ...
    })

    t.Run("Delete", func(t *testing.T) {
        // ...
    })
}

并行子测试

func TestParallel(t *testing.T) {
    tests := []struct {
        name  string
        input string
    }{
        {"case1", "input1"},
        {"case2", "input2"},
        {"case3", "input3"},
    }

    for _, tt := range tests {
        tt := tt // 捕获循环变量
        t.Run(tt.name, func(t *testing.T) {
            t.Parallel() // 并行运行子测试
            result := Process(tt.input)
            // 断言...
            _ = result
        })
    }
}

测试助手 (Test Helpers)

助手函数

func setupTestDB(t *testing.T) *sql.DB {
    t.Helper() // 将此函数标记为测试助手函数

    db, err := sql.Open("sqlite3", ":memory:")
    if err != nil {
        t.Fatalf("failed to open database: %v", err)
    }

    // 测试结束时清理
    t.Cleanup(func() {
        db.Close()
    })

    // 运行迁移
    if _, err := db.Exec(schema); err != nil {
        t.Fatalf("failed to create schema: %v", err)
    }

    return db
}

func assertNoError(t *testing.T, err error) {
    t.Helper()
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }
}

func assertEqual[T comparable](t *testing.T, got, want T) {
    t.Helper()
    if got != want {
        t.Errorf("got %v; want %v", got, want)
    }
}

临时文件与目录

func TestFileProcessing(t *testing.T) {
    // 创建临时目录 - 自动清理
    tmpDir := t.TempDir()

    // 创建测试文件
    testFile := filepath.Join(tmpDir, "test.txt")
    err := os.WriteFile(testFile, []byte("test content"), 0644)
    if err != nil {
        t.Fatalf("failed to create test file: %v", err)
    }

    // 运行测试
    result, err := ProcessFile(testFile)
    if err != nil {
        t.Fatalf("ProcessFile failed: %v", err)
    }

    // 断言...
    _ = result
}

Golden Files (对比文件测试)

针对存储在 `testdata/` 中的预期输出文件进行测试。

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

func TestRender(t *testing.T) {
    tests := []struct {
        name  string
        input Template
    }{
        {"simple", Template{Name: "test"}},
        {"complex", Template{Name: "test", Items: []string{"a", "b"}}},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got := Re
Read more
Ships witheverything-claude-code

🌐 Language / 语言 / 語言 为 AI 智能体(Agent)框架打造的性能优化系统。源自 Anthropic 黑客松获胜作品。 这不仅仅是配置文件。它是一个完整的系统:包含技能(Skills)、本能(Instincts)、内存优化、持续学习、安全扫描以及研究优先的开发模式。这些生产级的智能体(Agents)、钩子(Hooks)、命令(Commands)、规则(Rules)以及 MCP 配置,是在构建真实产品的 10 个多月高强度日常使用中演化而来的。 适用于 Claude Code, Codex,

Get the whole plugin