How to Get the Code Coverage Data Into SonarQube

The code coverage is an important part of the quality metrics of SonarQube. Unfortunately, SonarQube needs some extra steps to use our code coverage reports from our Azure DevOps pipeline as part of its code analysis.

As in the last posts on code coverage, we again use Coverlet and ReportGenerator as part of our Azure DevOps build pipeline.

 

Check that you collect code coverage

Especially if you have a dedicated build pipeline for SonarQube, make sure that you run dotnet test with the --collect:"XPlat Code Coverage" option:

 

Set the coverage report location

The first SonarQube-specific task is “Prepare Analysis Configuration“. Expand the Advanced section and add the location of our coverage report:

The prepare analysis step offers us a place to set additional properties for SonarQube.

 

Create a coverage report for SonarQube

After the testing task and before the Run Code Analysis step for SonarQube we can insert a ReportGenerator task. Here it is important to set the target directory to coveragereport and use SonarQube as the Report type:

Make sure you use the same directory that you specify in the first SonarQube task and set the Report type to SonarQube

For the Reports value we again set the two possible locations for the code coverage files:

 

Run the pipeline

If you now start your Sonar build job, it will build your application, run the tests, create the code coverage files, and turns them into a generic report for SonarQube. After a few minutes, the code coverage should show up in the SonarQube report:

You now see the code coverage inside SonarQube.

 

Conclusion

It took me a while to figure out how to specify the location for the report and what format I had to use. With this combination of Coverlet, ReportGenerator and SonarQube you get your code coverage as part of your quality metrics into the SonarQube dashboard. I hope this little guide saves you a lot of time.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.