January 2020
Intermediate to advanced
640 pages
16h 56m
English
At the end of the day, nothing precludes us from combining these two approaches into a hybrid approach that gives us the best of both worlds: the terseness of table-driven tests and the selective targeting of subtests.
To achieve this, we need to define our table-driven specs, just like we did before. Following that, we iterate the spec list and spawn a subtest for each test case. Here's how we could adapt our FizzBuzz tests so that they follow this pattern:
func TestFizzBuzzTableDrivenSubtests(t *testing.T) { specs := []struct { descr, exp string input int }{ {descr: "evenly divisible by 3", input: 9, exp: "Fizz"}, {descr: "evenly divisible by 3 and 5", input: 15, exp: "FizzBuzz"}, {descr: "edge case", input: 0