模糊测试入门 (Fuzzing)
单元测试只能测试你想到的情况,而模糊测试能帮你发现你没想到的边界情况。 1. 什么是模糊测试? 模糊测试 (Fuzzing) 是一种自动化测试技术,通过生成大量随机或半随机的输入数据来测试程序,寻找崩溃、panic、死循环等异常。 传统测试 vs 模糊测试: 1// 传统单元测试:测试已知的输入 2func TestAdd(t *testing.T) { 3 if Add(2, 3) != 5 { 4 t.Error("2 + 3 should be 5") 5 } 6} 7 8// 模糊测试:测试大量随机输入 9func FuzzAdd(f *testing.F) { 10 f.Fuzz(func(t *testing.T, a, b int) { 11 result := Add(a, b) 12 // 检查属性而不是具体值 13 if result < a && result < b { 14 t.Errorf("Add(%d, %d) = %d, should be >= both", a, b, result) 15 } 16 }) 17} 2. 编写 Fuzz 测试 2.1 基础示例 假设我们有一个解析 URL 的函数: 1// url.go 2package myurl 3 4import ( 5 "fmt" 6 "strings" 7) 8 9func ParseURL(rawURL string) (string, error) { 10 if !strings.HasPrefix(rawURL, "http://") && !strings.HasPrefix(rawURL, "https://") { 11 return "", fmt.Errorf("invalid protocol") 12 } 13 return rawURL, nil 14} 编写 Fuzz 测试: ...