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:
1 |
dotnet test --collect:"XPlat Code Coverage" |
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:
1 |
sonar.coverageReportPaths=coveragereport/SonarQube.xml |
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:
For the Reports value we again set the two possible locations for the code coverage files:
1 |
tests/**/coverage.cobertura.xml;$(Agent.TempDirectory)/**/coverage.cobertura.xml |
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:
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.