Search code examples
c#asp.netvisual-studio-2010opencover

Branch coverage with foreach?


I've got a simple method that calculate the total from a collection.

public void MethodToTest(Collection<int> collection)
{
    int sum = 0;
    foreach (int value in collection)
    {
        sum += value;
    }
}

The goal is to get a 100% at branch coverage using the opencoverage tool run in command line. I also got an Unit test that call the method MethodToTest :

[TestMethod]
public void TestMethodToTest()
{
    BomProviderMock mock = new BomProviderMock();
    BomManager bomManager = new BomManager(mock);

    List<int> list = new List<int>();
    for (int i = 0; i <= Int16.MaxValue; i++)
    {
        list.Add(i);
    }
    // Firts attempt with a non empty collection
    bomManager.MethodToTest(new Collection<int>(list));

    // Second attempt with an empty collection
    bomManager.MethodToTest(new Collection<int>());
}

After having used the tool opencover, the method MethodToTest got a 80% at branch coverage. My question is, does the foreach loop affect the branch coverage, if so, how can I get a 100% with this simple code?


Solution

  • I've Updated your question a bit, using some linq instead of the foreach loops. It takes a random number (same size list though), so the compiler won't "whisk it away" and have to compute it.

    I would suggest doing something with the sum in the method, or returning it, it might change your results.

    Last, but not least, don't obsess about 100%. It'll never happen in a real life big project. Just make sure you test the things that might brake, and build your software with testing in mind, so it'll be easy to do.

    void Main()
    {
        Random r = new Random();
        List<int> list = Enumerable.Range(1,Int16.MaxValue)
                                   .Select (e => r.Next(0,Int16.MaxValue))
                                   .ToList();
    
        // Firts attempt with a non empty collection
        MethodToTest(new Collection<int>(list));
    
        // Second attempt with an empty collection
        MethodToTest(new Collection<int>());
    }
    
    // Define other methods and classes here
    public void MethodToTest(Collection<int> collection)
    {
        var sum = collection.Sum (i => i);
        // do something with it. If you're just voiding it and it doesn't get 
        // used, it might be removed by compiler.
    }