.Net Posts

How to obtain code coverage of .Net code using OpenCover (an open source tool) and generate report using ReportGenerator tool.

While developing K2 Applications we may come across situations where might have to write .Net custom code to achieve some customizations depending upon customer requirements. And when we go for custom code some customers will be sceptical about the quality of code and the testcases that we write for this custom code. They will depend on this code coverage reports to determine the quality and for release metrics.

Today we are going to see

  • How to create Class library
  • How to create testcases using NUnit
  • How to obtain CodeCoverage using OpenCover
  • How to generate Coverage Report using ReportGenerator

 

Step 1: Create a Class Library.

Open Visual Studio, Create New Project, Select Class Library under Templates -> Visual C# -> Windows. Give project a name, here I have given as POC.Calculator.ClassLibrary add a new class with name as calculator and below is the code. Basically, it has some mathematical methods like addition, subtraction etc

    public class Calculator
    {
        //Adds 2 integers and returns sum
        public int Add(int num1, int num2)
        {
            return num1 + num2;
        }
        // adds 2 double values and returns double
        public double add(double num1, double num2)
        { 
            return num1 + num2; 
        }
        //Subtracts one value from other and returns difference
        public int subtract(int num1, int num2)
        {
            return (num1 > num2) ? num1 - num2 : num2 - num1;
        }
        //Returns square of the number
        public int Square(int num)
        {
            return num * num;
        }
        // Multiply two integers and retuns the result 
        public int Multiply(int num1, int num2)
        {
            return num1 * num2;
        }
        //performing Division on two float variables. 
        public float Division(float num1, float num2)
        {
            return num1 / num2;
        }
        public string add(string string1, string string2)
        {
            return string.Concat(string1, string2);
        }
    }

Once the code is written build it to create the DLL (Class Library)

Step 2: Create Test Cases using NUnit

Right Click on Solution, add new Project, Select Unit Test Project under section Visual C# -> Test, give a name. Here I’ve given it as POC.Calculator.UnitTests and the class name as CalculatorTests

Now using Nuget package manager console, install Nunit using below command. Also add the reference of class library that we created in step 1.

Install-Package NUnit -Version 3.10.1

Now write the unit test methods to test the methods in calculator class library. Below are the sample methods that I have written

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework.Api;
using POC.Calculator.ClassLibrary;
namespace POC.Calculator.UnitTests
{
    [TestClass]
    public class CalculatorTests
    {
        Calculator.ClassLibrary.Calculator objCalc = 
                           new Calculator.ClassLibrary.Calculator();
        [TestMethod]
        //Test to check Add integers Method
        public void Calculator_AddIntegers_ShouldReturnSum()
        {
            NUnit.Framework.Assert.AreEqual(objCalc.Add(5, 3), 8);
        }
        [TestMethod]
        //Test to check Add double Method
        public void Calculator_AddDouble_ShouldReturnSum()
        {
            NUnit.Framework.Assert.AreEqual(objCalc.Add(5.5, 3.5), 9);
        }
        [TestMethod]
        //Test to check get square Method
        public void Calculator_Square_ShouldReturnSquare()
        {
            NUnit.Framework.Assert.AreEqual(objCalc.Square(5), 25);
        }
        [TestMethod]
        //Test to check get multiply Method
        public void Calculator_MultiplyByZero_ShouldReturnZero()
        {
            NUnit.Framework.Assert.AreEqual(objCalc.Multiply(5, 0), 0);
        }
        [TestMethod]
        //Test to check get difference Method
        public void Calculator_GetDifference_ShouldReturnDifference()
        {
            NUnit.Framework.Assert.AreEqual(objCalc.Subtract(5, 0), 5);
        }
        [TestMethod]
        //Test to check division Method
        public void Calculator_DivideByZero_ShouldReturnArithmeticException()
        {
            Exception ex = null;
            try
            {
                objCalc.Division(5, 0);
            }
            catch (Exception e)
            {
                ex = e;
            }
            NUnit.Framework.Assert.AreEqual(ex, new ArithmeticException());
        }
        [TestMethod]
        //Test to check add strings Method
        public void Calculator_AddString_ShouldReturnConcatenatedString()
        {
            NUnit.Framework.Assert.AreEqual(objCalc.Add("ABC", "XYZ"), "ABCXYZ");
        }
    }
}

 

Now build the project and once it gets succeeded you will see all the test methods in TestExplorer Window. See Below Screenshot

1.TestExplorerTests

You can run them from here and check whether their execution is successful or not. If test passed successfully then a green tick mark will appear beside test name, if failed then a red cross mark.

2.TestExplorerTestsPassed

If you want to group certain tests together, then we can create OrderedTest. To create an ordered test just right click on the project, select add & and select OrderedTest.

7.OrderedTest

Now select the tests that you want group and add them to next window. You can set the execution sequence of tests using the arrows beside the window.

8.OrderedTestList

That’s it. Name it properly and just save the ordered test and you can see it in test explorer window.

9.UnitTestsExplorer

Now let’s see the other 2 steps together

Step 3: Obtaining Code Coverage using OpenCover
Step 4: Generating Coverage Report using ReportGenerator

Now download both tools from any of below links

OpenCover Tool

https://sourceforge.net/projects/opencover.mirror/
https://github.com/OpenCover/opencover/releases/tag/4.6.519

ReportGenerator Tool

https://danielpalme.github.io/ReportGenerator/

Once the download completes create a new folder in the project solution folder with name UnitTestScriptsAndReports.

3.jpg

Now inside this folder create a new batch file (.bat extension) and copy below code inside the batch file and save it. Here I have given the name as Calculator_UnitTestScript.

Batch file code
REM Create a 'GeneratedReports' folder if it does not exist
if not exist "%~dp0GeneratedReports" mkdir "%~dp0GeneratedReports" 

REM Remove any previous test execution files to prevent issues overwriting
IF EXIST "%~dp0Calculator.trx" del "%~dp0Calculator.trx%"

REM Remove any previously created test output directories
CD %~dp0
FOR /D /R %%X IN (%USERNAME%*) DO RD /S /Q "%%X" 

REM Run the tests against the targeted output
call :RunOpenCoverUnitTestMetrics

REM Generate the report output based on the test results
if %errorlevel% equ 0 (
 call :RunReportGeneratorOutput
)

REM Launch the report
if %errorlevel% equ 0 (
 call :RunLaunchReport
)

exit /b %errorlevel%
:RunOpenCoverUnitTestMetrics
"C:\Downloads\opencover.4.6.519\OpenCover.Console.exe" ^
-register:user ^
-target:"C:/Program Files (x86)/Microsoft Visual Studio 14.0/Common7/IDE/MSTest.exe" ^
-targetargs:"/testcontainer:\"C:/Users/Vijay/Documents/visual studio 2015/Projects/POC.Calculator.ClassLibrary/POC.Calculator.UnitTests/bin/Debug/POC.Calculator.UnitTests.dll"\" ^

 -filter:" +[POC.Calculator.ClassLibrary*]* -[POC.Calculator.UnitTests]*" ^

 -hideskipped:File;Attribute ^

-mergeoutput ^
-mergebyhash ^
-skipautoprops ^
-output:"%~dp0GeneratedReports\Calculator.xml"

exit /b %errorlevel% 
:RunReportGeneratorOutput
"C:\Downloads\ReportGenerator_2.5.1.0\ReportGenerator.exe" ^
-reports:"%~dp0GeneratedReports\Calculator.xml" ^
-targetdir:"%~dp0GeneratedReports\ReportGenerator_Output"
exit /b %errorlevel%

:RunLaunchReport
start "report" "%~dp0/GeneratedReports/ReportGenerator_Output/index.htm"
exit /b %errorlevel%

 

**Note

  • Now above code needs to be changed according to your project, just need to change the names and paths accordingly in highlighted places.
  • At –targetargs you need to give the path of unittests project dll.

*SubNote

Here in this case we are executing all unit tests of the project which is the reason we are giving the path of the dll. If we want to execute only certain test cases then we must give ordered test path.

(C:/Users/Vijay/Documents/visual studio 2015/Projects/POC.Calculator.ClassLibrary/POC.Calculator.UnitTests/bin/Debug/CalculatorTests.orderedtest)

  • At Filter attribute “+” indicates including the file for test coverage, “-“ indicates removing the file from test coverage. Above I have included whole project first and removed the unit tests project from coverage. So, we will get only the coverage of class library project (i.e. Calculator.cs)

Once changes are done save the batch file and run as admin, once it runs successfully it will generate 2 folders with names GeneratedReports & TestResults and opens the coverage report in browser.

See below screen shots.

4.GeneratedFolder.jpg

 

  • Batch file generates an xml file with coverage results using OpenCover.exe tool and this xml file will be used as an input to ReportGenerator.exe tool for creating the reports.
  • Report will be available in folder GeneratedReports\ReportGenerator_Output with name index.htm

Coverage Report

5.CoverageReport

Report gives you complete line coverage & branch coverage of your unit tests for class library. You can click on the Class library link and see where the coverage is missing. It will show covered lines in green colour and uncovered lines in red colour. See below screen shot

6.FullReport

That’s it folks, this is how we can create unit tests and get the code coverage of .Net Code and improve the code quality metrics.

*********************Next Post***********************

Modifying WebApi Default Route using Route Attribute

While creating webApi’s default route/URL of the api will be some thing like below

https://[ServerName]:[Port]/api/[ControllerMethod]?[QueryParamerters]

 Now if we want to change this route as per our customization there are multiple ways to achieve but the easiest way is to use Route Attribute.

Example Method:

public class WorkListController : ApiController
{
  public List<WorkListData> Get(string UserName = "", string Status = "")
  {
    //Code to return data
  }
}

 

Now for this WorkList Controller the default the route/URL that is being created is below

** As Controller has only one Get Method, it will be considered as Default method in api

https://[ServerName]:[Port]/api/WorkList?UserName=Vijay&Status=Approved

Now Modifying URL Route Attribute:

[Route("TaskList/MyTasks ")]
public class WorkListController : ApiController
{
  public List<WorkListData> Get(string UserName = "", string Status = "")
  {
   //Code to return data
  }
}

Now the Route will be modified as below

https://[ServerName]:[Port]/TaskList/MyTasks?UserName=Vijay&Status=Approved

 

 

Advertisements

One thought on “.Net Posts”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s