go-testlisted
Install: claude install-skill omeyang/Thoth
# Go 测试专家
为 Go 代码编写高质量测试:$ARGUMENTS
---
## 1. 表驱动测试(必须使用)
对于任何逻辑函数,使用表驱动模式,易于扩展。
```go
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
want int
wantErr bool
}{
{"positive", 1, 2, 3, false},
{"negative", -1, -1, -2, false},
{"overflow", math.MaxInt, 1, 0, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Add(tt.a, tt.b)
if (err != nil) != tt.wantErr {
t.Fatalf("Add() error = %v, wantErr %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("Add() = %v, want %v", got, tt.want)
}
})
}
}
```
### 测试覆盖率目标
- 核心业务逻辑:≥95%
- 整体覆盖率:≥90%
- 必须覆盖:正常路径、边界条件、错误路径
### 测试命名规范
- 函数:`Test<Function>_<Scenario>`
- 子测试:清晰描述意图
- 示例:`TestParse_EmptyInput`, `TestConnect_Timeout`
---
## 2. HTTP 测试(httptest)
**不要**启动完整服务器,直接测试 handler。
```go
func TestHandleCreateUser(t *testing.T) {
// 注入 mock 依赖
srv := NewServer(mockDB, mockLogger)
// 构造请求
body := `{"name":"Alice","email":"alice@example.com"}`
req := httptest.NewRequest("POST", "/users", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
// 记录响应
w := httptest.NewRecorder()
// 直接调用 handler
srv.ServeHTTP(w, req)
// 断言
if w.Code != http.StatusCreated {
t.Errorf("expected status 201, got %d", w.Code)
}
// 验证响