测试与调试

概述

测试和调试是保证代码质量的重要环节。Go 语言内置了测试框架,提供了丰富的测试和性能分析工具。本部分将详细讲解如何编写测试代码和调试程序。

章节内容

39. 单元测试

单元测试是代码质量的基础保障。本章讲解:

  • testing 包使用
  • 测试函数命名
  • 表格驱动测试
  • 测试覆盖率
  • Mock 和 Stub

40. 性能调优

性能优化需要科学的分析方法。本章涵盖:

  • 基准测试
  • pprof 性能分析
  • CPU 分析
  • 内存分析
  • 常见优化技巧

41. 调试技巧

调试是定位问题的关键技能。本章介绍:

  • 使用 Delve 调试
  • 日志记录
  • 错误追踪
  • 常见问题定位
  • 调试工具推荐

学习要点

单元测试

// 测试文件 xxx_test.go
func TestAdd(t *testing.T) {
    result := Add(2, 3)
    if result != 5 {
        t.Errorf("Add(2, 3) = %d; want 5", result)
    }
}

// 表格驱动测试
func TestDivide(t *testing.T) {
    tests := []struct {
        a, b     int
        expected int
        hasError bool
    }{
        {10, 2, 5, false},
        {10, 0, 0, true},
    }
    for _, tt := range tests {
        result, err := Divide(tt.a, tt.b)
        if tt.hasError && err == nil {
            t.Error("expected error")
        }
        if !tt.hasError && result != tt.expected {
            t.Errorf("got %d, want %d", result, tt.expected)
        }
    }
}

基准测试

func BenchmarkProcess(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Process()
    }
}

pprof 使用

import _ "net/http/pprof"

func main() {
    go func() {
        http.ListenAndServe(":6060", nil)
    }()
    // 程序逻辑
}
# CPU 分析
go tool pprof http://localhost:6060/debug/pprof/profile

# 内存分析
go tool pprof http://localhost:6060/debug/pprof/heap

# Web 界面
go tool pprof -http=:8080 cpu.prof

Delve 调试

# 安装
go install github.com/go-delve/delve/cmd/dlv@latest

# 调试
dlv debug ./main.go

# 常用命令
break main.main    # 设置断点
continue           # 继续执行
next               # 单步执行
print var          # 打印变量

学习建议

  1. 先写测试:采用测试驱动开发(TDD)
  2. 保持测试独立:测试之间不应有依赖
  3. 覆盖边界情况:测试正常和异常情况
  4. 定期运行测试:提交前运行所有测试
  5. 分析性能瓶颈:优化前先分析