Unit testing 多返回值函数的表测试
我在路上切牙,在深入研究之后,我遇到了以下问题: 我有一个返回多个值的函数Unit testing 多返回值函数的表测试,unit-testing,testing,go,Unit Testing,Testing,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 } 我知道对于half(1)来说,返回值应该是0,false,对于half(2)来说,它应该匹配1,
// 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>},
}
只需向结构中添加另一个字段,该字段保存第二个返回值。例如:
var halfTests = []struct {
in int
out1 int
out2 bool
}{
{1, 0, false},
{3, 1, true},
}
您的测试功能如下所示:
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)
}
}
}
用适当格式的建议编辑问题。
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)
}
}
}