Fizz Buzz in Golang

A basic implementation of the infamous Fizz Buzz with unit testing.

Setting up the test

Set up fizz_buzz_test.go with the following file:

1package fizzbuzz
2
3import "testing"
4
5func 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}
17
18func 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}
24
25func 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}
31
32// BenchmarkFizzBuzz() is a benchmarking function. These functions follow the
33// form `func BenchmarkXxx(*testing.B)` and can be used to test the performance
34// of your implementation. They may not be present in every exercise, but when
35// 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/op
41//
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 same
45// exercise, keep in mind that others will run the same benchmarks on different
46// machines, with different specs, so the results from these benchmark tests may
47// vary.
48func BenchmarkFizzBuzz(b *testing.B) {
49 for i := 0; i < b.N; i++ {
50 FizzBuzz(15)
51 }
52}

Fizz Buzz implementation

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

Running Tests

In the directory, run go test.