Azure DevOps - Easy Code coverage
In all projects you develop in .NETCore, it is essential to add a test project :-) And then it becomes very simple to complete this project with a code coverage calculation procedure. Developers will be asked to create test procedures that go through all the branches of your source code. A code coverage rate of at least 80% is very often recommended.
From Visual Studio
From Visual Studio or via a command line, you can calculate the code coverage using these instructions :
-
Install the NuGet Coverlet.MSBuild package to your test project. It is used by the compiler to generate the Coverage file via the
dotnet test
command. -
Install these two tools, in order to have the commands for generating and formatting HTML code coverage files.
dotnet tool install --global coverlet.console dotnet tool install --global dotnet-reportgenerator-globaltool
-
Add the following cmd file to your project and run it whenever you want.
echo off REM 1. Install Coverlet.MSBuild Nuget Package in the project. REM REM 2. Install tools: REM $:\> dotnet tool install --global coverlet.console REM $:\> dotnet tool install --global dotnet-reportgenerator-globaltool REM REM Use this command to list existing installed tools: REM $:\> dotnet tool list --global echo on cls dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura reportgenerator "-reports:coverage.cobertura.xml" "-targetdir:C:\Temp\Coverage" -reporttypes:HtmlInline_AzurePipelines start "" "C:\Temp\Coverage\index.htm"
From Azure DevOps
In your Build Definition, add these three steps:
-
Test and Code Coverage executes the
dotnet test
command, specifying to compile the code with the PDB files and the summary filecoverage.cobertura.xml
containing the code coverage information. -
Generate reports transforms the previous xml file into a series of easily readable HTML documents.
-
Publish code coverage publishes the summary (xml) file and all HTML files to the Azure DevOps server.
Each developer can run the code coverage locally, but can also view it from Azure DevOps by clicking on the Code Coverage tab.
# Test (including PDB) and generate Code Coverage
- task: DotNetCoreCLI@2
displayName: 'Test and Code Coverage'
inputs:
command: test
projects: '**/*[Tt]ests/*.csproj'
arguments: '--configuration $(BuildConfiguration) /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:DebugType=Full'
publishTestResults: true
# Coverage Generation
- task: reportgenerator@4
displayName: Generate reports
inputs:
reports: '**/coverage.cobertura.xml'
targetdir: 'CoverageTrotting'
reporttypes: 'HtmlInline_AzurePipelines'
# Publish code coverage
- task: PublishCodeCoverageResults@1
displayName: 'Publish code coverage'
inputs:
codeCoverageTool: Cobertura
summaryFileLocation: '**/coverage.cobertura.xml'
reportDirectory: CoverageTrotting