在Go中进行单元测试时,是否可以动态断言两个值是否相等?

时间:2017-05-10 15:54:54

标签: unit-testing testing go testify

我刚刚开始使用Go。我正在编写单元测试,我希望能够使用表进行测试,其中与实际结果进行比较的结果有时应该或不应该相等。

例如,这是我目前拥有的代码:

package main

import (
    "github.com/stretchr/testify/assert"
    "testing"
)

func TestFunc(t *testing.T) {
    tables := []struct {
        input               string
        comparisonResult    string
        shouldBeEqual       bool
    }{
        {
            "some irrelevant input",
            "some result",
            true,
        },
        {
            "some other irrelevant input",
            "some other result",
            false,
        },
    }

    for _, table := range tables {
        actualResult := sampleFunc(table.input)
        if table.shouldBeEqual {
            assert.Equal(t, table.expectedResult, actualResult)
        } else {
            assert.NotEqual(t, table.expectedResult, actualResult)
        }
    }
}

现在,这并不是太糟糕,但如果最后一点可以更改为更清晰的东西以获得更好的可读性,那就更好了:

for _, table := range tables {
    actualResult := sampleFunc(table.input)
    assert.EqualOrNotEqual(t, table.comparisonResult, actualResult, table.shouldBeEqual)
}

因此,如果table.comparisonResultactualResult相等,则第一个测试应该通过,如果两个相等,则第二个测试应该通过。

我查看了testify/assert docs并且我认为我找不到类似于我上面编写的假EqualOrNotEqual函数的函数,但也许我不小心跳过了某些东西,或者有一些我不知道的Go特殊语法可能会帮助我实现这一目标。

注意:我很清楚我可以为此编写自己的功能。我的理由是因为如果这是一个完善的模式,那么包/库通常将它作为内置函数包含在内,有时可能没有记录/埋没在文档中。如果没有,也许我不应该这样做,或者可能有更好的方法。开始使用新语言起初是非常劳动密集型的,尤其是因为你必须学习所有新的习语和怪癖以及正确的做事方式。

1 个答案:

答案 0 :(得分:2)

由于它只是为了可读性,而且由于看起来这个函数不存在,你可以将你的工作代码复制粘贴到一个单独的函数中:

func equalOrNotEqual(t TestingT, expected, actual interface{}, shouldBeEqual bool) {
    if shouldBeEqual {
        assert.Equal(t, expected, actual)
    } else {
        assert.NotEqual(t, expected, actual)
    }
}

for _, table := range tables {
    actualResult := sampleFunc(table.input)
    equalOrNotEqual(t, table.comparisonResult, actualResult, table.shouldBeEqual)
}