Chapter 14 - Automated Testing
Exercise 3: Table-Driven Tests
Replace all your tests with a table-driven test:
- Create a
testDatatype with fields for the argument to pass toOrdinaland the return value you want. - Create a slice of
testDatavalues representing the various arguments you want to pass and the return values you expect to see. - Loop over each
testDatavalue in the slice:- Pass the argument field from the
testDatatoOrdinal, 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
package ordinals
import (
"testing"
)
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)
}
}
}Output:
--- FAIL: TestThree (0.00s)
ordinals_test.go:31: Ordinal(3) = "3th", want "3rd"
FAIL
FAIL github.com/jaymcgavren/ordinals 0.007s