你应该在循环中做一个 assert 语句吗?

Joã*_*ida 8 testing

当我们想要测试给定方法的多个值时,我们是否应该在单个测试中遍历这些值?

或者它是不正确的,因为在失败的情况下可能更难确定原因?

像这样的东西:

testSomething(){
    List myValues = {'value1', 'value2', 'value3', ...}

    for(value: myValues){
        assertTrue(Something(Value))
    }
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*esT 8

Not if you can avoid it

By which I mean, depending on what you're using to do your unit tests, you might not be able to realistically avoid it. In that case, do as needs must

If you run your assert in a loop, you effectively have one test which is testing an arbitrary number of things. That's going to get confusing.

What you want is multiple tests which test one thing each.

Some test frameworks (like NUnit for C#) allow you to define a test that takes parameters and then define the values to repeat the test with.

e.g.

[TestCase(1, 1, 2)]
[TestCase(2, 3, 5)]
[TestCase(0, -1, -1)]
public void MyTest(int a, int b, int expected) {        
    Assert.AreEqual(expected, a + b);
}
Run Code Online (Sandbox Code Playgroud)

If your framework supports that, it's wonderfully easy to do.

或者,如果您使用脚本语言(例如 javascript),您可能能够在循环中定义测试,而不是断言。

例如

describe('My tests', function() {
    var testCases = [
        {a: 1, b: 1, expected: 2},
        {a: 2, b: 3, expected: 5},
        {a: 0, b: -1, expected: -1}
    ]

    testCases.forEach(function(t) {
        it(`Adds ${t.a} and ${t.b} correctly`, function() {
            assert.equal(t.expected, t.a + t.b);
        });
    });
})
Run Code Online (Sandbox Code Playgroud)

这定义了许多测试,测试单个事物。没有一项测试可以测试很多东西。这随后使查看哪个失败时更容易。