tablespoon
A simple approach to executing table-based tests using Go 1.7's new subtests.
Basically, the idea is:
- Define a type
T
that implements the one-methodFixture
interface, doing all the input/output verification in that method - Declare your test tables as a
map[string]Fixture
, where the key is a descriptive name for what that particular row is testing - Pass the
t *testing.T
, themap[string]Fixture
, and the func totbsp.RunTableTest()
- PROFIT 🎉 🎉 🎉 🎉 ✨ 🎉 🎉 🎉 ✨ ✨ 🎉
So, it'll look something like this:
// The func we're testing
func Sq(x int) int {
return x * x
}
// The data fixture we use for the test - a "row" in the "table"
type sqfix struct {
in, out int
}
// The method to actually do the testing
func (fix sqfix) Test(t *testing.T, name string) bool {
got := Sq(fix.in)
if got != fix.out {
t.Errorf("Expected %v when squaring %v, got %v", fix.out, fix.out, got)
}
return false
}
func TestSq(t *testing.T) {
table := map[string]tbsp.Fixture{
"x=1": sqfix{in: 1, out: 1},
"x=2": sqfix{in: 2, out: 4},
"x=3": sqfix{in: 3, out: 9},
"x=4": sqfix{in: 4, out: 16},
"x=5": sqfix{in: 5, out: 25},
}
tbsp.RunTableTest(t, table)
}
Note: this is so trivial to do that it's probably a terrible idea as a library, but it demonstrates how TBTs should, now, probably be run to take advantage of subtests.