Back to home

Setting up the testFizz Buzz implementationRunning Tests
Go Fizzbuzz main image

Go Fizzbuzz

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:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 package fizzbuzz import "testing" func TestReturnString(t *testing.T) { expected := "2" if observed := FizzBuzz(2); observed != expected { t.Fatalf("FizzBuzz(2)) = %v, want %v", observed, expected) } } func TestFizz(t *testing.T) { expected := "Fizz" if observed := FizzBuzz(3); observed != expected { t.Fatalf("FizzBuzz(3)) = %v, want %v", observed, expected) } } func TestBuzz(t *testing.T) { expected := "Buzz" if observed := FizzBuzz(5); observed != expected { t.Fatalf("FizzBuzz(5)) = %v, want %v", observed, expected) } } func TestFizzBuzz(t *testing.T) { expected := "FizzBuzz" if observed := FizzBuzz(15); observed != expected { t.Fatalf("FizzBuzz(15)) = %v, want %v", observed, expected) } } // BenchmarkFizzBuzz() is a benchmarking function. These functions follow the // form `func BenchmarkXxx(*testing.B)` and can be used to test the performance // of your implementation. They may not be present in every exercise, but when // they are you can run them by including the `-bench` flag with the `go test` // command, like so: `go test -v --bench . --benchmem` // // You will see output similar to the following: // // BenchmarkFizzBuzz 2000000000 0.46 ns/op // // This means that the loop ran 2000000000 times at a speed of 0.46 ns per loop. // // While benchmarking can be useful to compare different iterations of the same // exercise, keep in mind that others will run the same benchmarks on different // machines, with different specs, so the results from these benchmark tests may // vary. func BenchmarkFizzBuzz(b *testing.B) { for i := 0; i < b.N; i++ { FizzBuzz(15) } }

Fizz Buzz implementation

We will use the interger-to-ASCII function itoa from the strings library.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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.

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.