Search⌘ K
AI Features

FizzBuzz: "FizzBuzz" Requirement

Explore how to use the Red-Green-Refactor cycle in TDD to implement the FizzBuzz feature. Learn to write effective tests that handle divisibility by 3, 5, and both, simplify code logic, and optimize your test suite while maintaining full coverage.

The last feature that we have to implement is the FizzBuzz feature. Let’s recap the scenarios we’ve managed so far

  • Return Fizz if the number is divisible by 3.
  • Return Buzz if the number is divisible by 5.
  • Return the string representation of the number if not divisible neither by 3 nor by 5.

Now, let’s focus on what we missed to complete the kata.

FizzBuzz scenario

We have to manage the numbers that are divisible by 3 and also by 5. When we receive one of these numbers, we need to return the FizzBuzz string to the caller.

The Red phase

Let’s write one test to jump into the Red phase:

package fizzbuzz

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestFizzBuzz(t *testing.T) {
	// arrange
	testSuite := []struct {
		name     string
		input    int
		expected string
	}{
		{
			"ShouldReturnOne_WhenOneIsPassed",
			1,
			"1",
		},
		{
			"ShouldReturnTwo_WhenTwoIsPassed",
			2,
			"2",
		},
		{
			"ShouldReturnFour_WhenFourIsPassed",
			4,
			"4",
		},
		{
			"ShouldReturnFizz_WhenThreeIsPassed",
			3,
			"Fizz",
		},
		{
			"ShouldReturnFizz_WhenSixIsPassed",
			6,
			"Fizz",
		},
		{
			"ShouldReturnBuzz_WhenFiveIsPassed",
			5,
			"Buzz",
		},
		{
			"ShouldReturnFizzBuzz_WhenFifteenIsPassed",
			15,
			"FizzBuzz",
		},
	}

	for _, tt := range testSuite {
		t.Run(tt.name, func(t *testing.T) {
			// act
			got := FizzBuzz(tt.input)

			// assert
			assert.Equal(t, tt.expected, got)
		})
	}
}
Red phase for the value 15
...