Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 多返回值函数的表测试_Unit Testing_Testing_Go - Fatal编程技术网

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)
        }
    }
}