10

When we have multiple values for which we would like to test a given method should we loop through the values in a single test?

Or is it incorrect as in case of failure it might be harder to identify the cause?

Something like this:

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

    for(value: myValues){
        assertTrue(Something(Value))
    }
}

1 Answer 1

9

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

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

Alternatively, if you're using a script language (e.g. javascript), you might be able to define your tests in a loop, rather than the asserts.

e.g.

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

This defines many tests, testing a single thing. Not one test testing many things. Which subsequently makes it much easier to see which one fails when it does.

2
  • I just want to double check, if we must use an assert in a for loop, one or more failed assertions will cause the entire unit test to fail, correct? I want to make sure that if I have 100,000 items in a list I'm iterating, the first 99,999 asserts fail, but the last one (100,000th) passes, the unit test will still fail, correct?.
    – Steve3p0
    Jul 24, 2019 at 18:40
  • If your asserts are in one test, the test will fail if any assert fails.
    – JamesT
    Jul 25, 2019 at 8:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.