单元测试与基准测试
Go单元测试与基准测试详解:go test -bench。
1. 单元测试
// user_test.go
func TestUserCreation(t *testing.T) {
u := NewUser("Alice", 30)
if u.Name != "Alice" {
t.Errorf("expected Alice, got %s", u.Name)
}
}
// 表驱动测试
func TestAdd(t *testing.T) {
tests := []struct {
a, b, expected int
}{
{1, 2, 3},
{0, 0, 0},
{-1, 1, 0},
}
for _, tt := range tests {
if got := Add(tt.a, tt.b); got != tt.expected {
t.Errorf("Add(%d, %d) = %d, want %d", tt.a, tt.b, got, tt.expected)
}
}
}
2. 基准测试
func BenchmarkSort(b *testing.B) {
data := make([]int, 10000)
for i := range data { data[i] = rand.Int() }
b.ResetTimer()
for i := 0; i < b.N; i++ {
sort.Ints(data)
}
}
运行:
go test -bench=. -benchmem
# BenchmarkSort-8 5000 320 ns/op 0 B/op 0 allocs/op
3. 子测试
func TestParallel(t *testing.T) {
t.Run("case1", func(t *testing.T) {
t.Parallel()
// ...
})
}
4. 覆盖率
go test -coverprofile=coverage.out
go tool cover -html=coverage.out