Go 测试模式
遵循 TDD 方法论,用于编写可靠、可维护测试的全面 Go 测试模式。
何时激活
- 编写新的 Go 函数或方法时
- 为现有代码添加测试覆盖率时
- 为性能关键代码创建基准测试时
- 为输入验证实现模糊测试时
- 在 Go 项目中遵循 TDD 工作流时
Go 的 TDD 工作流
红-绿-重构循环
RED → 首先编写一个失败的测试
GREEN → 编写最少的代码来通过测试
REFACTOR → 改进代码,同时保持测试通过
REPEAT → 继续处理下一个需求
Go 中的分步 TDD
// Step 1: Define the interface/signature
// calculator.go
package calculator
func Add(a, b int) int {
panic("not implemented") // Placeholder
}
// Step 2: Write failing test (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)
}
}
// Step 3: Run test - verify FAIL
// $ go test
// --- FAIL: TestAdd (0.00s)
// panic: not implemented
// Step 4: Implement minimal code (GREEN)
func Add(a, b int) int {
return a + b
}
// Step 5: Run test - verify PASS
// $ go test
// PASS
// Step 6: Refactor if needed, verify tests still pass
表驱动测试
Go 测试的标准模式。以最少的代码实现全面的覆盖。
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"positive numbers", 2,…