Search⌘ K
AI Features

FizzBuzz: "Fizz" Requirement

Explore writing tests and implementing the Fizz requirement in FizzBuzz using test-driven development in Go. Understand how to handle numbers divisible by 3 with iterative Red-Green-Refactor steps to build flexible, passing code.

Fizz scenario

So far, we’ve only dealt with the not divisible scenario, which only covers the numbers not divisible by 3 and 5. In this lesson, let’s build the Fizz feature.

Handling input 3

As a reminder, our function should give back Fizz when the number passed is divisible by 3.

The Red phase

To obey the TDD constraints, we need to start writing a test that will take us to the Red stage:

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",
		},
	}

	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 of "3"

To get into the Red area, we added another test to our testSuite variable. This test ...