Understanding and maintaining the code coverage is one of the most important aspect of writing unit tests and ensures the code quality with respect to functional points . Once you write the Unit tests in Visual Studio and manage them using Test Explorer, the next immediate job for you would be understand what code you have tested so far using the test cases ? Code Coverage let us determine which portion / section of the code has been tested. By analyzing the result, we can determine if the code is tested for all certain scenarios or we need write more test cases to covers some of the scenarios for the code block.
If you look back to the first articles of this series of posts, How to write your very first Unit Test in Visual Studio using MSTest Framework easily ? , we wrote the following code block to add two positive number and corresponding unit test.
Once we run the test method, While the unit test is passing, we need to check if our unit test covers the all code block for our method using the “Code Coverage”.
You can start Analyze the “Code Coverage” from
- Test—> Analyze Code Coverage –> Selected Tests/ All Tests
- Right Click on Test from Test explorer / or To any group –> Analyze Code Coverage for Selected Test
Once the test execution successful, Visual Studio calculate the code coverage and display it within “Code Coverage Results” windows; as shown in below image. Here you can see the code coverage for “mytestclass.dll” is around 84.62% . Which means, it does not cover all the code block.
You can take a granular look of covered block by expanding the class – The coverage would display for individual methods. This will give you a clear picture on which part of code you still need to check with your unit test.
The “Code Coverage Analysis” tool provides an externally useful features by visually indicating the Covered, Partially Covered, Not Covered code block. You can enable this feature by selecting the “Show Code Coverage Coloring” option in the “Code Coverage Results” dialog window.
By Selecting this option, once you navigate through the code block, the color highlights indicate which is
- covered ( light blue)
- partially covered ( light orange)
- not covered (light red)
Now, from this color highlighting you can see what part is missing from your unit test case. As per our actual logic, which is nothing but testing the code with both negative parameters. To cover that part of code using your unit test, you can just add another test method that pass two negative values.
In this case of test method the if statement of actual code block will execute. Now if you run the code coverage tool again, you should get 100% covered blocks for all your code you have written.
Hope this will help you to understand the code coverage and write better unit test.