Monday, September 21, 2015

Is VS-Code coverage tool is more perfect than NCover ?



Today we were using NCover to measure code coverage of our unit test. It was showing 100% coverage for few functions where it’s 80% in same function using Visual Studio code coverage tool.
We investigate little and found that, the % is getting change if there are more than return branch in function. 

Let’s discuss the real scenario here. Here is our sample code which we will test using VS unit test.

public class TestClass
{
    public string ReturnData(int id)
    {
        return (id == 1) == true ? "Hello" : "hi";
    }
}

So, ReturnData function has two possible exit path. Now, we will write unit test for same.

[TestClass]
    public class UnitTestClass
    {
        [TestMethod]
        public void Test_Function()
        {
            Assert.AreEqual("Hello", new TestClass().ReturnData(1));
           
        }
    }

Now, here is code coverage measurement using NCover.




And here is code coverage checking using Visual Studio.





It’s showing that unit test could not able to cover 100% code. Because we did test of ReturnData() function by passing 1 which will execute certain branch. To make it 100%, we need to pass such parameter so that the other branch gets covered.
We can modify our test case like below.

[TestMethod]
        public void Test_Function()
        {
            Assert.AreEqual("Hello", new TestClass().ReturnData(1));
            Assert.AreEqual("hi", new TestClass().ReturnData(0));         
        }

Now, it’s showing that code coverage is 100%.


 

No comments:

Post a Comment