Skip to content
Development
Command

/go-test

为 Go 强制执行测试驱动开发(TDD)工作流。先编写表格驱动测试(Table-Driven Tests),然后进行实现。使用 go test -cover 验证 80% 以上的覆盖率。

From plugin
everything-claude-code
1.8k35 skills15 agents35 commands6 hooks
Install
> /plugin marketplace add xu-xiang/everything-claude-code-zh
> /plugin install everything-claude-code@everything-claude-code

How it fires

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

  • Fires itselfClaude auto-loads it when your prompt matches the work.
  • You can call itInvoke it directly when you want it.
  • Slash command/go-test

Context preview

What this command does when you run it.

为 Go 强制执行测试驱动开发(TDD)工作流。先编写表格驱动测试(Table-Driven Tests),然后进行实现。使用 go test -cover 验证 80% 以上的覆盖率。

Command definition

go-test.md
description: 为 Go 强制执行测试驱动开发(TDD)工作流。先编写表格驱动测试(Table-Driven Tests),然后进行实现。使用 go test -cover 验证 80% 以上的覆盖率。

Go TDD 命令

此命令通过惯用的 Go 测试模式为 Go 代码强制执行测试驱动开发(TDD)方法论。

此命令的作用

1. **定义类型/接口**:首先搭建函数签名脚手架 2. **编写表格驱动测试**:创建全面的测试用例(红灯 RED) 3. **运行测试**:验证测试因正确的原因而失败 4. **编写代码**:编写最少量的代码以通过测试(绿灯 GREEN) 5. **重构(Refactor)**:在保持测试通过的同时改进代码 6. **检查覆盖率**:确保 80% 以上的覆盖率

何时使用

在以下场景使用 `/go-test`:

  • 实现新的 Go 函数
  • 为现有代码添加测试覆盖率
  • 修复 Bug(先编写失败的测试)
  • 构建关键业务逻辑
  • 学习 Go 中的 TDD 工作流

TDD 周期

RED      → 编写失败的表格驱动测试
GREEN    → 编写最少量的代码以通过测试
REFACTOR → 改进代码,保持测试通过
REPEAT   → 下一个测试用例

会话示例

用户:/go-test 我需要一个验证电子邮件地址的函数

智能体(Agent):
# TDD 会话:电子邮件验证器(Email Validator)

## 第 1 步:定义接口

```go
// validator/email.go
package validator

// ValidateEmail 检查给定的字符串是否为有效的电子邮件地址。
// 如果有效则返回 nil,否则返回描述问题的错误。
func ValidateEmail(email string) error {
    panic("not implemented")
}

第 2 步:编写表格驱动测试(红灯 RED)

// validator/email_test.go
package validator

import (
    "testing"
)

func TestValidateEmail(t *testing.T) {
    tests := []struct {
        name    string
        email   string
        wantErr bool
    }{
        // 有效的电子邮件
        {"simple email", "user@example.com", false},
        {"with subdomain", "user@mail.example.com", false},
        {"with plus", "user+tag@example.com", false},
        {"with dots", "first.last@example.com", false},

        // 无效的电子邮件
        {"empty string", "", true},
        {"no at sign", "userexample.com", true},
        {"no domain", "user@", true},
        {"no local part", "@example.com", true},
        {"double at", "user@@example.com", true},
        {"spaces", "user @example.com", true},
        {"no tld", "user@example", true},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            err := ValidateEmail(tt.email)
            if tt.wantErr && err == nil {
                t.Errorf("ValidateEmail(%q) = nil; want error", tt.email)
            }
            if !tt.wantErr && err != nil {
                t.Errorf("ValidateEmail(%q) = %v; want nil", tt.email, err)
            }
        })
    }
}

第 3 步:运行测试 - 验证失败(FAIL)

$ go test ./validator/...

--- FAIL: TestValidateEmail (0.00s)
    --- FAIL: TestValidateEmail/simple_email (0.00s)
        panic: not implemented

FAIL

✓ 测试按预期失败(panic)。

第 4 步:编写最少量代码(绿灯 GREEN)

// validator/email.go
package validator

import (
    "errors"
    "regexp"
)

var emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)

var (
    ErrEmailEmpty   = errors.New("email cannot be empty")
    ErrEmailInvalid = errors.New("email format is invalid")
)

func ValidateEmail(email string) error {
    if email == "" {
        return ErrEmailEmpty
    }
    if !emailRegex.MatchString(email) {
        return ErrEmailInvalid
    }
    return nil
}

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

$ go test ./validator/...

PASS
ok      project/validator    0.003s

✓ 所有测试均通过!

第 6 步:检查覆盖率

$ go test -cover ./validator/...

PASS
coverage: 100.0% of statements
ok      project/validator    0.003s

✓ 覆盖率:100%

TDD 完成!


## 测试模式

### 表格驱动测试(Table-Driven Tests)
```go
tests := []struct {
    name     string
    input    InputType
    want     OutputType
    wantErr  bool
}{
    {"case 1", input1, want1, false},
    {"case 2", input2, want2, true},
}

for _, tt := range tests {
    t.Run(tt.name, func(t *testing.T) {
        got, err := Function(tt.input)
        // 断言(assertions)
    })
}

并行测试(Parallel Tests)

for _, tt := range tests {
    tt := tt // 变量捕获(Capture)
    t.Run(tt.name, func(t *testing.T) {
        t.Parallel()
        // 测试主体
    })
}

测试助手(Test Helpers)

func setupTestDB(t *testing.T) *sql.DB {
    t.Helper()
    db := createDB()
    t.Cleanup(func() { db.Close() })
    return db
}

覆盖率命令

# 基础覆盖率
go test -cover ./...

# 覆盖率配置文件
go test -coverprofile=coverage.out ./...

# 在浏览器中查看
go tool cover -html=coverage.out

# 按函数查看覆盖率
go tool cover -func=coverage.out

# 启用竞态检测
go test -race -cover ./...

覆盖率目标

| 代码类型 | 目标 | |-----------|--------| | 关键业务逻辑 | 100% | | 公共 API | 90%+ | | 通用代码 | 80%+ | | 生成的代码 | 排除 |

TDD 最佳实践

**应该(DO):**

  • 在任何实现之前,先编写测试
  • 每次更改后运行测试
  • 使用表格驱动测试以获得全面的覆盖率
  • 测试行为,而非实现细节
  • 包含边缘情况(空值、nil、最大值)

**不该(DON'T):**

  • 在测试之前编写实现
  • 跳过红灯(RED)阶段
  • 直接测试私有函数
  • 在测试中使用 `time.Sleep`
  • 忽视不稳定的测试(Flaky tests)

相关命令

  • `/go-build` - 修复构建错误
  • `/go-review` - 实现后评审代码
  • `/verify` - 运行完整的验证循环

相关

  • 技能(Skill):`skills/golang-testing/`
  • 技能(Skill):`skills/tdd-workflow/`
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