Chapter 14 - Automated Testing

Exercise 2: Test Helper Methods

Write a helper function for your tests that accepts these parameters:

  • The argument passed to Ordinal.
  • The actual return value from Ordinal.
  • The expected return value.

It should return a string in this format (without square brackets):

Ordinal([input]) = "[actual]", want "[expected]"

Update your tests for the calls Ordinal(1), Ordinal(2), and Ordinal(3) to use this helper function.

Solution

$GOPATH/src/github.com/jaymcgavren/ordinals/ordinals_test.go

package ordinals

import (
	"fmt"
	"testing"
)

func TestOne(t *testing.T) {
	argument := 1
	want := "1st"
	got := Ordinal(argument)
	if got != want {
		t.Error(errorString(argument, got, want))
	}
}

func TestTwo(t *testing.T) {
	argument := 2
	want := "2nd"
	got := Ordinal(argument)
	if got != want {
		t.Error(errorString(argument, got, want))
	}
}

func TestThree(t *testing.T) {
	argument := 3
	want := "3rd"
	got := Ordinal(argument)
	if got != want {
		t.Error(errorString(argument, got, want))
	}
}

func errorString(argument int, got string, want string) string {
	return fmt.Sprintf("Ordinal(%d) = \"%s\", want \"%s\"",
		argument, got, want)
}

Output:

--- FAIL: TestThree (0.00s)
	ordinals_test.go:31: Ordinal(3) = "3th", want "3rd"
FAIL
FAIL	github.com/jaymcgavren/ordinals	0.007s