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 toOrdinal
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
toOrdinal
, and record the return value you got. - If the return value you got doesn’t match the expected return value field from the
testData
, callt.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.)
- Pass the argument field from the
Solution
$GOPATH/src/github.com/jaymcgavren/ordinals/ordinals_test.go
Output:
--- FAIL: TestThree (0.00s)
ordinals_test.go:31: Ordinal(3) = "3th", want "3rd"
FAIL
FAIL github.com/jaymcgavren/ordinals 0.007s