Skip to content

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.Run subtests
  • testadv2 — fuzzing with func FuzzXxx(*testing.F) (seed corpus runs under go test; try go test -fuzz=Fuzz)
  • testadv3 — handler testing with net/http/httptest

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)
}

Source

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)

Source

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)
}

Source

testadv4 — benchmarks

Show hint
Implement the sum; the benchmark uses b.Loop():
total := 0; for _, n := range nums { total += n }; return total

Source