Go Test Fuzz
In this tutorial, you'll learn about Go Test: Fuzzing. We cover key concepts, practical examples, and best practices.
Fuzz testing -- Use Go's built-in fuzz testing to automatically discover edge cases and bugs.
The Problem
Fuzz testing generates random inputs and feeds them to your function. Go 1.18+ has built-in fuzz support with the Fuzz testing function.
Wrong
func TestReverse(t *testing.T) {
// Testing with known cases but missing edge cases
tests := []struct{ in, want string }{
{"hello", "olleh"},
{"", ""},
}
}
Output:
// May miss edge cases like unicode, control chars
Right
func FuzzReverse(f *testing.F) {
testcases := []string{"hello", "world", " "}
for _, tc := range testcases {
f.Add(tc) // Seed corpus
}
f.Fuzz(func(t *testing.T, orig string) {
rev := Reverse(orig)
doubleRev := Reverse(rev)
if orig != doubleRev {
t.Errorf("Before: %q, after: %q", orig, doubleRev)
}
})
}
Output:
$ go test -fuzz=FuzzReverse
// Finds unicode issues automatically
Prevention
- Fuzz tests use FuzzXxx naming
- Add seed corpus with f.Add()
- Run with go test -fuzz=FuzzName
- Crashes saved to testdata/fuzz/
- Run continuously until cancelled (Ctrl+C)
Common Mistakes with test fuzz
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro