3 ms·
Pfft, you know how tests for functions like this: func MonthToString(month int) string { switch month { case 1: return "January" ca
by Joker_vD 2y ago
Pfft, you know how tests for functions like this:
func MonthToString(month int) string {
switch month {
case 1: return "January"
case 2: return "February"
...
case 10: return "October"
case 12: return "December"
default: panic(fmt.Errorf("invalid month number: %d", month))
}
}
are usually written? You take the switch's body, shove it into the test function, and then replace "case/return" with regexp to "assert.Equal" or something:
func TestMonthToString(t *testing.T) {
assert.Equal(t, "January", MonthToString(1))
assert.Equal(t, "February", MonthToString(2))
...
assert.Equal(t, "October", MonthToString(10))
assert.Equal(t, "December", MonthToString(12))
assert.PanicsWithError(t, "invalid month number: 13", func() { MonthToString(13) })
}
Look ma, we got that sweet 100% code coverage!
- BobbyTables2 2y agoI feel attacked! (:>
- nasretdinov 2y agoNice nick name. What happened to the first one?
- BobbyTables3 2y agoIt got dropped.
- nasretdinov 2y agoAgain??
- gus_massa 2y agoThe solution is to add integration testing, for (i=1, i<13, i++) { assert.Equal(t, i, StringToMonth(MonthToString(i))) } the reverse composition is harder to test.
- debugnik 2y agoDid you mean property testing?