【Go】堆和栈变量

点击阅读更多查看文章内容

1. 文件命名规则

  • 测试文件必须与被测文件同名,并加上 _test 后缀
    • 被测文件:calculator.go
    • 测试文件:calculator_test.go
  • 测试文件需放在同一包内
    • 若测试内部未导出函数,可使用 package packagename_test(需导入被测包)。

2. 测试函数签名

  • 函数名必须以 Test 开头,后接大写字母(如 TestAdd)。

  • 参数必须为 *testing.T

    1
    2
    3
    func TestAdd(t *testing.T) {
    // 测试逻辑
    }

3. 子测试(Subtests)

使用 t.Run() 创建嵌套测试,便于分组和选择性运行:

1
2
3
4
5
6
7
8
9
10
11
12
func TestMultiply(t *testing.T) {
t.Run("PositiveNumbers", func(t *testing.T) {
if Multiply(2, 3) != 6 {
t.Error("Expected 6")
}
})
t.Run("NegativeNumbers", func(t *testing.T) {
if Multiply(-2, 3) != -6 {
t.Fatal("Expected -6") // Fatal 会终止当前子测试
}
})
}

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

通过结构体切片定义多组输入和期望输出,减少重复代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func TestDivide(t *testing.T) {
tests := []struct {
name string
a, b float64
want float64
wantErr bool
}{
{"NormalCase", 6, 3, 2, false},
{"DivideByZero", 6, 0, 0, true},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Divide(tt.a, tt.b)
if (err != nil) != tt.wantErr {
t.Errorf("Divide() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("Divide() = %v, want %v", got, tt.want)
}
})
}
}

5. 断言与错误报告

  • 常用方法

    方法 用途
    t.Error() / t.Errorf() 标记失败但继续执行后续测试
    t.Fatal() / t.Fatalf() 标记失败并立即终止当前测试函数
    t.Log() 输出日志(仅在 -v 标志时显示)
  • 示例

    1
    2
    3
    4
    5
    6
    func TestSubtract(t *testing.T) {
    result := Subtract(5, 3)
    if result != 2 {
    t.Errorf("Expected 2, got %d", result)
    }
    }

6. 测试覆盖率

  • 生成覆盖率报告:

    1
    2
    go test -coverprofile=coverage.out
    go tool cover -html=coverage.out # 生成 HTML 可视化报告
  • 覆盖率模式
    -covermode=count(记录执行次数)或 set(仅记录是否执行)。


7. 基准测试(Benchmark)

  • 函数名以 Benchmark 开头,参数为 *testing.B

    对测试方法运行多次,得到方法运行时间等性能指标

    1
    2
    3
    4
    5
    func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
    Add(1, 2)
    }
    }
  • 运行基准测试:

    1
    go test -bench=. -benchmem  # 同时输出内存分配
作者

ShiHaonan

发布于

2025-04-21

更新于

2025-04-21

许可协议

评论