.NET Core, SonarQube and Code Coverage

Analyzing .Net applications in Azure DevOps (a.k.a. Visual Studio Team Services – short VSTS) and sending the results to SonarQube was pretty easy – but with .NET Core it has become quite a challenge.

Modify .csproj file

First of all you need to modify the project files you want to analyze. You have to add a ‘ProjectGuid’ element. This is a new guid.



  
    netcoreapp2.1
    Alegri.Cockpit
  

  
    full
    True
  

  
    <!-- SonarQube needs this - this is a new guide and has no associatons -->
    {478518D1-731B-40C6-ABB2-567303445596}
  

You can generate it with the following line:

[Guid]::NewGuid()

If you don’t want to analyse your test projects you just don’t add the attribute there.

Add “Prepare analysis on SonarQube” task to your pipeline

Add the task to your pipeline and configure your endpoint. For the code coverage to work you have to add the following attribute under Advanced:

Prepare Analysis

Configure test task

In the test task you have to add –collect:”Code Coverage” for the task to add a logger for code coverage.

Collect Code Coverage

Convert Code Coverage Files

This is the tricky part. The test task only generates .coverage files for each test project. But SonarQube needs a .coveragexml and does not understand the .coverage file format. To convert the file you have to call CodeCoverage.exe with the (undocumented) parameter /analyse. I’ve created a PowerShell script for that.

$ver = (Get-ChildItem $env:USERPROFILE\.nuget\packages\Microsoft.CodeCoverage | Select-Object -Property Name | Sort-Object -Descending | Select-Object -First 1).Name

Get-ChildItem -Recurse -Filter "*.coverage" | % {
$outfile = "$([System.IO.Path]::GetFileNameWithoutExtension($_.FullName)).coveragexml"
$output = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($_.FullName), $outfile)
"Analyse '$($_.FullName)' with output '$output'..."
. $env:USERPROFILE\.nuget\packages\microsoft.codecoverage\$ver\build\netstandard1.0\CodeCoverage\CodeCoverage.exe analyze /output:$output $_.FullName
}
"Done"

You can add this script in a PowerShell task as a inline script. Make sure the WorkingDirectory is the $(Agent.TempDirectory).

2018-09-22 10_32_53-

So that’s it.
Your .NET Core analysis should now show up in SonarQube including Code Coverage.

2018-09-22 10_34_28-Projects

One comment

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