Over the past week I've been trying to get some code/test coverage metrics from a new .NET Core project I've been working on. Because the RTM of .NET Core is still quite new not many code coverage tools support it. But I noticed in the .Net CoreFx library on Github that they're using OpenCover for their code coverage. So I pulled the code down from Github and had a look at how they'd implemented it (I love the new open source Microsoft).
Basically, what I wanted to achieve is a report on the test coverage in my sample project (the sample project can be found in Github). I've used the sample project from another post I did on API Design.
So let's begin at the end, here's the output I want to achieve:
All in all it's pretty simple to configure. You just need to the following pre-requisites installed:
- .Net Core CLI - Get this by installing the .NET Core SDK)
- OpenCover - Installed via Nuget
- ReportGenerator - Installed via Nuget.
Then in the sample project you'll see I've added a batch file to my test project, which is as follows:
@echo off SET dotnet="C:/Program Files/dotnet/dotnet.exe" SET opencover=C:\Users\simon\.nuget\packages\OpenCover\4.6.519\tools\OpenCover.Console.exe SET reportgenerator=C:\Users\simon\.nuget\packages\ReportGenerator\2.4.5\tools\ReportGenerator.exe SET targetargs="test" SET filter="+[*]SJCNet.APIDesign.* -[*.Test]* -[xunit.*]* -[FluentValidation]*" SET coveragefile=Coverage.xml SET coveragedir=Coverage REM Run code coverage analysis %opencover% -oldStyle -register:user -target:%dotnet% -output:%coveragefile% -targetargs:%targetargs% -filter:%filter% -skipautoprops -hideskipped:All REM Generate the report %reportgenerator% -targetdir:%coveragedir% -reporttypes:Html;Badges -reports:%coveragefile% -verbosity:Error REM Open the report start "report" "%coveragedir%\index.htm"
Essentially the above batch file runs an OpenCover command, which calls
dotnet test and generates the coverage results in Coverage.xml. Then it runs the ReportGenerator command that converts the Coverage.xml into a HTML report. The final line opens the report.