Testing Advanced
Advanced · Testing & Applied
Beyond a basic TestXxx, Go’s testing toolkit covers subtests, property-based
fuzzing, and HTTP handler testing.
- testadv1 — table-driven tests with
t.Runsubtests - testadv2 — fuzzing with
func FuzzXxx(*testing.F)(seed corpus runs undergo test; trygo test -fuzz=Fuzz) - testadv3 — handler testing with
net/http/httptest
Resources
Section titled “Resources”Exercises
Section titled “Exercises”testadv1 test
Section titled “testadv1 test”testadv1 — table-driven tests with t.Run
Show hint
Check divisibility by 15 first, then 3, then 5, else strconv.Itoa(n):
switch {case n%15 == 0: return "FizzBuzz"case n%3 == 0: return "Fizz"case n%5 == 0: return "Buzz"default: return strconv.Itoa(n)}testadv2 test
Section titled “testadv2 test”testadv2 — fuzzing
Show hint
Reverse by runes, not bytes:
r := []rune(s)for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] }return string(r)testadv3 test
Section titled “testadv3 test”testadv3 — httptest
Show hint
Write the body to the ResponseWriter and check the error:
if _, err := w.Write([]byte("pong")); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError)}testadv4 test
Section titled “testadv4 test”testadv4 — benchmarks
Show hint
Implement the sum; the benchmark uses b.Loop():
total := 0; for _, n := range nums { total += n }; return total