Monday, 4 March 2019

How to increase Unit Test code coverage in DotNetCore?

Hey let me tell you, if you are analyzing unit test coverage in Visual Studio and the scores is not good, this post is for you. Here I will tell you how to analyze the code coverage in visual studio?

First of all you would require Visual Studio Enterprise or else you can try Visual Studio 2019 Preview. In Visual studio Professional code coverage option not given.

Write some code and create unit test and verify it through
Test > Window > Test Explorer or try shortcut (Ctrl+E, T)

In the same Test tab you could find the Analyze Code Coverage Option.

After clicking on it you get complete code coverage details.
Now If you see your coverage score is poor, even if you have written unit test for you projects, don't worry. You project might include some core component or utility that you don't want to comes in coverage. Might be there are many private methods been declared that you want to exclude or some time you have also declared some constructor that you want to exclude.

I would recommend you to use [ExcludeFromCodeCoverageAttribute] attribute  that comes under
Namespace System.Diagnostics.CodeAnalysis, under the Assembly System.Diagnostics.Tools. You can
Apply this attribute on methods or on class to exclude.

If you want to test your private methods then you can try [Unit Testing for Private Methods in DotNet C#]

Some time you also need to refactor the code in such a way that code coverage will increase like:
Avoid return in mid of the implementation.