Gas*_*ton 3 testing unit-testing go
我在Go上切齿,在深入研究表驱动测试后,我遇到了以下问题:
我有一个返回多个值的函数
// 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
}
Run Code Online (Sandbox Code Playgroud)
我知道,对于half(1)返回值应该是0, false和half(2)它应该匹配1, true,但我似乎无法弄清楚如何将它放在一个表上.
怎么会有类似下面的东西?
var halfTests = []struct {
in int
out string
}{
{1, <0, false>},
{3, <1, true>},
}
Run Code Online (Sandbox Code Playgroud)
这样做还有其他更惯用的方法吗?
作为参考,这里使用表来测试类似于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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
只需在结构中添加另一个包含第二个返回值的字段.例:
var halfTests = []struct {
in int
out1 int
out2 bool
}{
{1, 0, false},
{3, 1, true},
}
Run Code Online (Sandbox Code Playgroud)
您的测试功能如下所示:
func TestHalf(t *testing.T) {
for _, tt := range halfTests {
s, t := half(tt.in)
if s != tt.out1 || t != tt.out2 {
t.Errorf("half(%d) => %d, %v, want %d, %v", tt.in, s, t, tt.out1, tt.out2)
}
}
}
Run Code Online (Sandbox Code Playgroud)