Chapter 14 - Automated Testing

Exercise 3: Table-Driven Tests

Replace all your tests with a table-driven test:

  • Create a testData type with fields for the argument to pass to Ordinal and the return value you want.
  • Create a slice of testData values representing the various arguments you want to pass and the return values you expect to see.
  • Loop over each testData value in the slice:
    • Pass the argument field from the testData to Ordinal, and record the return value you got.
    • If the return value you got doesn’t match the expected return value field from the testData, call t.Errorf.
    • Use the same format for the test failure string that you used for your helper function from the previous exercise. (Once you’re done, the helper function will be redundant, so you can delete it.)



package ordinals

import (

type testData struct {
	argument int
	want     string

func TestOrdinal(t *testing.T) {
	tests := []testData{
		testData{argument: 1, want: "1st"},
		testData{argument: 2, want: "2nd"},
		testData{argument: 3, want: "3rd"},
		testData{argument: 4, want: "4th"},
		testData{argument: 11, want: "11th"},
		testData{argument: 21, want: "21st"},
	for _, test := range tests {
		got := Ordinal(test.argument)
		if got != test.want {
			t.Errorf("Ordinal(%d) = \"%s\", want \"%s\"",
				test.argument, got, test.want)


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