4.4 测试与基准测试
testing 包
go
package main
import "testing"
// 测试函数
func TestAdd(t *testing.T) {
result := add(2, 3)
expected := 5
if result != expected {
t.Errorf("add(2, 3) = %d; expected %d", result, expected)
}
}
// 表格驱动测试
func TestAddTable(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"正数", 2, 3, 5},
{"负数", -1, -1, -2},
{"零", 0, 0, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := add(tt.a, tt.b)
if result != tt.expected {
t.Errorf("add(%d, %d) = %d", tt.a, tt.b, result)
}
})
}
}
// 并行测试
func TestParallel(t *testing.T) {
t.Parallel()
}
// Setup 和 Teardown
func TestWithSetup(t *testing.T) {
setup()
defer teardown()
}基准测试
go
// 基准测试函数
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
add(2, 3)
}
}
// 报告内存分配
func BenchmarkAddOptimized(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
add(2, 3)
}
b.ReportAllocs()
}
// 并行基准测试
func BenchmarkAddParallel(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
add(2, 3)
}
})
}示例测试
go
// 示例测试
func ExampleAdd() {
result := Add(2, 3)
fmt.Println(result)
// Output: 5
}
func ExampleGreet() {
result := Greet("World")
fmt.Println(result)
// Output: Hello, World!
}TestMain
go
func TestMain(m *testing.M) {
// Setup
setupTestDatabase()
// 运行测试
code := m.Run()
// Teardown
teardownTestDatabase()
os.Exit(code)
}测试覆盖率
bash
# 查看覆盖率
go test -cover
# 生成覆盖率报告
go test -coverprofile=coverage.out
go tool cover -html=coverage.out
# 查看每个函数的覆盖率
go tool cover -func=coverage.out