表测试多返回值函数

时间:2015-12-16 22:33:06

标签: unit-testing testing go

我在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>},
}

还有其他更惯用的方法吗?

作为参考,这里使用表来测试类似于FizzBu​​zz函数的东西:

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

1 个答案:

答案 0 :(得分:6)

只需在结构中添加另一个包含第二个返回值的字段。例如:

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)
        }
    }
}
相关问题