A basic implementation of the infamous Fizz Buzz with unit testing.
Set up fizz_buzz_test.go
with the following file:
1package fizzbuzz23import "testing"45func TestReturnString(t *testing.T) {6 expected := "2"7 if observed := FizzBuzz(2); observed != expected {8 t.Fatalf("FizzBuzz(2)) = %v, want %v", observed, expected)9 }10}11func TestFizz(t *testing.T) {12 expected := "Fizz"13 if observed := FizzBuzz(3); observed != expected {14 t.Fatalf("FizzBuzz(3)) = %v, want %v", observed, expected)15 }16}1718func TestBuzz(t *testing.T) {19 expected := "Buzz"20 if observed := FizzBuzz(5); observed != expected {21 t.Fatalf("FizzBuzz(5)) = %v, want %v", observed, expected)22 }23}2425func TestFizzBuzz(t *testing.T) {26 expected := "FizzBuzz"27 if observed := FizzBuzz(15); observed != expected {28 t.Fatalf("FizzBuzz(15)) = %v, want %v", observed, expected)29 }30}3132// BenchmarkFizzBuzz() is a benchmarking function. These functions follow the33// form `func BenchmarkXxx(*testing.B)` and can be used to test the performance34// of your implementation. They may not be present in every exercise, but when35// they are you can run them by including the `-bench` flag with the `go test`36// command, like so: `go test -v --bench . --benchmem`37//38// You will see output similar to the following:39//40// BenchmarkFizzBuzz 2000000000 0.46 ns/op41//42// This means that the loop ran 2000000000 times at a speed of 0.46 ns per loop.43//44// While benchmarking can be useful to compare different iterations of the same45// exercise, keep in mind that others will run the same benchmarks on different46// machines, with different specs, so the results from these benchmark tests may47// vary.48func BenchmarkFizzBuzz(b *testing.B) {49 for i := 0; i < b.N; i++ {50 FizzBuzz(15)51 }52}
We will use the interger-to-ASCII function itoa
from the strings
library.
package fizzbuzz import "strconv" // FizzBuzz should have a comment documenting it. func FizzBuzz(i int) string { switch true { case i%15 == 0: return "FizzBuzz" case i%3 == 0: return "Fizz" case i%5 == 0: return "Buzz" default: return strconv.Itoa(i) } }
In the directory, run go test
.