【发布时间】:2015-12-16 22:33:05
【问题描述】:
我正在使用 Go 语言,在深入了解 table driven tests 后遇到了以下问题:
我有一个返回多个值的函数
// Halves an integer and and returns true if it was even or false if it was odd.
func half(n int) (int, bool) {
h := n / 2
e := n%2 == 0
return h, e
}
我知道half(1) 的返回值应该是0, false,而half(2) 的返回值应该与1, true 匹配,但我似乎不知道如何将它放在桌子上。
如何才能拥有类似于以下内容的东西?
var halfTests = []struct {
in int
out string
}{
{1, <0, false>},
{3, <1, true>},
}
还有其他更惯用的方法吗?
作为参考,这里有一个类似于 FizzBuzz 函数的测试,使用表格:
var fizzbuzzTests = []struct {
in int
out string
}{
{1, "1"},
{3, "Fizz"},
{5, "Buzz"},
{75, "FizzBuzz"},
}
func TestFizzBuzz(t *testing.T) {
for _, tt := range fizzbuzzTests {
s := FizzBuzz(tt.in)
if s != tt.out {
t.Errorf("Fizzbuzz(%d) => %s, want %s", tt.in, s, tt.out)
}
}
}
【问题讨论】:
标签: unit-testing testing go