Testing verifies software behavior by supplying defined inputs and conditions, then comparing the observed result with an expected result. In Go, unit testing uses built-in tooling and supports maintainable test suites without third-party software. section 6.0 section 6.3
Build a practical unit test by following this pattern:
- Represent scenarios as a table containing inputs, conditions, and expected outputs. section 6.3.1
- Loop over the scenarios and call the function under test for each one. section 6.3.1
- Fail with diagnostic output when the actual result differs from the expected result. section 6.3.1
- Run the suite with go test, then expand the table with additional cases. section 6.3.1
Finding a Fizz Buzz defect
A table-driven Test_FizzBuzz supplies 37 as input and compares the returned string with the expected sequence. Running go test exposes differences in spacing, separators, and boundary output; correcting either the implementation or expected data produces a passing suite. Adding cases for 5 and 12 then checks smaller, targeted sequences. section 6.3.1
Listing 6.12 Basic Fizz Buzz
package main
import (
"fmt"
"strings"
"strconv"
)
func main() {
var input string
fmt.Println("Enter a number for fizzbuzz")
fmt.Scanln(&input) #1
numInput, err := strconv.ParseInt(input, 10, 16)
if err != nil {
panic("that's not a number!")
}
result := fizzbuzz(numInput) #2
fmt.Println("result:", result)
}
func fizzbuzz(n int64) string {
var fizzbuzzes []string
for i := int64(0); i < n; i++ { #3
v := ""
isThree := i % 3 == 0
isFive := i % 5 == 0
if isThree && isFive {
v = "Fizz Buzz"
} else if isThree {
v = "Fizz"
} else if isFive {
v = "Buzz "
} else {
v = fmt.Sprintf("%d", i)
}
fizzbuzzes = append(fizzbuzzes, v)
}
return strings.Join(fizzbuzzes, " ")
}
Inspect the complete Fizz Buzz implementation that supplies the behavior tested by the table-driven suite. section 6.3.1




















































