【问题标题】:Table tests for multi-return value function多返回值函数的表测试
【发布时间】: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>},
}

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

作为参考,这里有一个类似于 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)
        }
    }
}

【问题讨论】:

    标签: unit-testing testing go


    【解决方案1】:

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

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

    【讨论】:

    • 使用格式正确的建议编辑了问题。
    猜你喜欢
    • 2017-02-04
    • 2019-12-11
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 2018-03-24
    相关资源
    最近更新 更多