I want to show test coverage for my .NET 5 unit tests in my local SonarQube instance (on Windows).
dotnet sonarscanner begin /k:"MyProject" /d:sonar.host.url="http://localhost:9000" /d:sonar.login="<token>" /d:sonar.cs.opencover.reportsPaths="**\TestResults\*\*.xml"
dotnet build
dotnet test --no-build --collect:"XPlat Code Coverage"
dotnet sonarscanner end /d:sonar.login="<token>"
The dotnet test
command generates the coverage reports as coverage.cobertura.xml
files in the <TestProjectDir>.TestResults\<some-guid>\
folder.
In the logs I can see the following warning:
WARN: Could not import coverage report '<MyTestProject>\TestResults\a4af5812-7f80-469b-8876-3ea0c7c4c98d\coverage.cobertura.xml' because 'Missing root element <CoverageSession> in C:\Users\<Path>\TestResults\a4af5812-7f80-469b-8876-3ea0c7c4c98d\coverage.cobertura.xml at line 2'. Troubleshooting guide: https://community.sonarsource.com/t/37151
Following the link from the warning message, I can see that only Visual Studio Code Coverage, dotCover and OpenCover/Coverlet are supported. As far as I can tell from their GitHub page, is OpenCover/Coverlet is "XPlat Code Coverage".
In my test projects the coverlet.collector
NuGet package v 3.0.3 is installed.
What am I missing?
I found this related question: SonarQube: Unable to import test coverage but it doesn't help me because I can't use dotCover.
After a lot of trial and error, here's the solution that worked for me.
I had to install the lastest version of dotnet-sonarscanner
and dotnet-reportgenerator-globaltool
for this to work. I already had the report generator installed, but needed to update it to use the SonarQube report type.
dotnet tool install --global dotnet-sonarscanner --version 5.2.0
dotnet tool update dotnet-reportgenerator-globaltool -g --version 4.8.7
With the reportgenerator
the cobertura files can be converted to the SonarQube format.
dotnet sonarscanner begin /k:"MyProject" /d:sonar.host.url="http://localhost:9000" /d:sonar.login="<token>" /d:sonar.coverageReportPaths=".\sonarqubecoverage\SonarQube.xml"
dotnet build
dotnet test --no-build --collect:"XPlat Code Coverage"
reportgenerator "-reports:*\TestResults\*\coverage.cobertura.xml" "-targetdir:sonarqubecoverage" "-reporttypes:SonarQube"
dotnet sonarscanner end /d:sonar.login="<token>"
Report generator supported file formats: https://github.com/danielpalme/ReportGenerator#supported-input-and-output-file-formats
SonarQube generic test data format: https://docs.sonarqube.org/latest/analysis/generic-test/