Is it a bad practice to run unit tests in a loop?

I am writing some unit tests in C # using nunit. Consider the following code:

    [Test ()]
    public void TestCarCost () {
        for (int i = 0; i < Examples.exampleCount; i++) {
            Car car = new Car(Examples[i]);
            Assert.AreEqual (car.getCost (), Examples[i].cost, "Test " + (i + 1) + " failed");
        }
    }

Let's say the examples are a class with some static data to test various possible input data for car types, as you can see that I'm trying to check for any errors in the car.getCost () function. Now, when this in the loop is misunderstood, because, for example, when any of the statements fails, it always sends you to one line of code. Moreover, as far as I can tell, whenever a statement fails in [Test ()] nunit, it immediately terminates the rest of the test code. This means that if I have everything inside the loop and claim that nr 1 fails, I don’t see that the other statements failed. When writing explicitly, all tests essentially write code with copying, so it also doesn't feel good.What can be considered good practice in this situation? Is it good to have a ton of similar code in unit testing? Is there some elegant solution that I am missing?

+4
source share
2 answers

Better to use TestCaseAttributeinstead of a loop. Read more in the link .

In your case should be:

[TestCase(1)]
[TestCase(2)]
[TestCase(3)]
public void TestCarCost (int id) 
{           
    Car car = new Car(Examples[id]);
    Assert.AreEqual (car.getCost (), Examples[id].cost, "Test " + (i + 1) + " failed");

}

Here you can create several test cases for one test method. For each test case, you can specify a parameter in the attribute TestCase()and pass it as idin your test method.

Based on this, idyou can access your resources, which are in your case `Examples [id]. ''

I would prefer to use this method because I can control every case and does not require additional logic.

, unit test, , .

+5

NUnit . (.. , , string), TestCase - :

[TestCase("Example Value 1", ExpectedResult=123.4)]
[TestCase("Example Value 2", ExpectedResult=567.8)]
[TestCase("Example Value 3", ExpectedResult=901.2)]
public void TestCarCost (string exampleValue) {
    Car car = new Car(exampleValue);
    return car.GetCost();        
}

( , ) , TestCaseSource, , :

[TestCaseSource(nameof(Examples))]
public void TestCarCost (ExampleInput exampleValue) {
    Car car = new Car(exampleValue);
    return car.GetCost();        
}

public IEnumerable<ITestCaseData> Examples {
    get {
        yield return new TestCaseData(new ExampleInput(1,2)).Returns(123.4);
        yield return new TestCaseData(new ExampleInput(3,4)).Returns(567.8);
        yield return new TestCaseData(new ExampleInput(5,6)).Returns(901.2);
    }
}
+7

Source: https://habr.com/ru/post/1671652/


All Articles