Search⌘ K
AI Features

FizzBuzz: Not-Divisible Requirement

Explore how to apply test-driven development to the FizzBuzz function for inputs not divisible by three or five. Learn to write focused tests in the Red phase, implement minimal code changes in the Green phase, and improve test clarity and structure through refactoring. Discover how to simplify your code by converting input to strings and organizing tests using table-driven approaches to reduce duplication and enhance readability.

As a reminder, let’s recap the rules of the FizzBuzz kata. It’s a function that accepts a number as the input and returns a string depending on the following conditions:

  • If the number is divisible by three, it returns Fizz.
  • If the number is divisible by five, it returns Buzz.
  • If the number is divisible by three and five, it returns FizzBuzz.
  • If the number is neither divisible by three nor by five, it returns a string representation of that number.

So far, we managed the most trivial example which used 1 as the input argument. Now, let’s add more tests for the fourth requirement.

Passing 2 to the FizzBuzz function

Let’s start with a simple scenario for the FizzBuzz function, which consists of passing the value 2 to it.

The Red phase

package fizzbuzz

import (
	"strconv"
	"testing"

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

func TestFizzBuzz(t *testing.T) {
	// arrange
	input := 1

	// act
	got := FizzBuzz(input)

	// assert
	assert.Equal(t, strconv.Itoa(input), got)
}

func TestFizzBuzz_Two(t *testing.T) {
	// arrange
	input := 2

	// act
	got := FizzBuzz(input)

	// assert
	if got != "2" {
		t.Errorf(`expected "2" but got %q`, got)
	}
}
Red phase for the value of 2

Here, we’re back in the Red stage of the TDD cycle. Our solution works fine with the 1 value, but it’s wrong ...