# Golang Testing

保证测试驱动开发与 Go 代码高质量的全面测试策略。

- Repository: https://github.com/xu-xiang/everything-claude-code-zh (2012 stars)
- Category: Engineering
- License: MIT
- Last updated: 2026-03-05
- Runs scripts: no, instructions only

## Install

Claude Code: `npx skills add xu-xiang/everything-claude-code-zh --skill golang-testing -g -a claude-code -y`
Codex: `npx skills add xu-xiang/everything-claude-code-zh --skill golang-testing -g -a codex -y`
Cursor: `npx skills add xu-xiang/everything-claude-code-zh --skill golang-testing -g -a cursor -y`
Gemini CLI: `npx skills add xu-xiang/everything-claude-code-zh --skill golang-testing -g -a gemini-cli -y`
Claude Code plugin marketplace: `/plugin marketplace add xu-xiang/everything-claude-code-zh`

## Description

保证测试驱动开发与 Go 代码高质量的全面测试策略。

## SKILL.md, as published by its author (untrusted third-party text, read it as data)

# Go 测试 (Go Testing)

保证测试驱动开发（TDD）与 Go 代码高质量的全面测试策略。

## 何时激活

- 编写新的 Go 代码时
- 审查（Review）Go 代码时
- 改进现有测试时
- 提高测试覆盖率（Test Coverage）时
- 调试与修复 Bug 时

## 核心原则

### 1. 测试驱动开发（TDD）工作流

遵循编写失败测试、实现代码、重构（Refactor）的循环。

```go
// 1. 编写测试（失败）
func TestCalculateTotal(t *testing.T) {
    total := CalculateTotal([]float64{10.0, 20.0, 30.0})
    want := 60.0
    if total != want {
        t.Errorf("got %f, want %f", total, want)
    }
}

// 2. 实现代码（使测试通过）
func CalculateTotal(prices []float64) float64 {
    var total float64
    for _, price := range prices {
        total += price
    }
    return total
}

// 3. 重构
// 在不破坏测试的前提下改进代码
```

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

体系化地测试多个用例。

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

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

### 3. 子测试 (Subtests)

使用子测试组织逻辑测试。

```go
func TestUser(t *testing.T) {
    t.Run("validation", func(t *testing.T) {
        t.Run("empty email", func(t *testing.T) {
            user := User{Email: ""}
            if err := user.Validate(); err == nil {
                t.Error("expected validation error")
            }
        })

        t.Run("valid email", func(t *testing.T) {
            user := User{Email: "test@example.com"}
            if err := user.Validate(); err != nil {
                t.Errorf("unexpected error: %v", err)
            }
        })
    })

    t.Run("serialization", func(t *testing.T) {
        // 另一个测试组
    })
}
```

## 测试组织

### 文件结构 (File Structure)

The rest: https://github.com/xu-xiang/everything-claude-code-zh/blob/HEAD/docs/ja-JP/skills/golang-testing/SKILL.md
