测试和调试是保证代码质量的重要环节。Go 语言内置了测试框架,提供了丰富的测试和性能分析工具。本部分将详细讲解如何编写测试代码和调试程序。
单元测试是代码质量的基础保障。本章讲解:
性能优化需要科学的分析方法。本章涵盖:
调试是定位问题的关键技能。本章介绍:
单元测试:
// 测试文件 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 # 打印变量