edd*_*dex 15 c# unit-testing code-coverage sonarqube
我想在本地 SonarQube 实例(在 Windows 上)中显示 .NET 5 单元测试的测试覆盖率。
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>"
Run Code Online (Sandbox Code Playgroud)
该dotnet test命令将覆盖率报告生成为文件夹coverage.cobertura.xml中的文件<TestProjectDir>.TestResults\<some-guid>\。
在日志中我可以看到以下警告:
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
通过警告消息中的链接,我可以看到仅支持Visual Studio Code Coverage、dotCover和OpenCover/Coverlet 。据我从他们的GitHub 页面可以看出,OpenCover/Coverlet是“XPlat 代码覆盖率”。
在我的测试项目中,coverlet.collector安装了 NuGet 包 v 3.0.3。
我缺少什么?
我发现了这个相关问题:SonarQube: Unable to import test Coverage但这对我没有帮助,因为我无法使用dotCover。
edd*_*dex 20
经过大量的试验和错误,这是对我有用的解决方案。
我必须安装最新版本的dotnet-sonarscanner和dotnet-reportgenerator-globaltool才能正常工作。我已经安装了报告生成器,但需要更新它以使用 SonarQube 报告类型。
dotnet tool install --global dotnet-sonarscanner --version 5.2.0
dotnet tool update dotnet-reportgenerator-globaltool -g --version 4.8.7
Run Code Online (Sandbox Code Playgroud)
使用reportgeneratorcobertura 文件可以转换为SonarQube 格式。
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>"
Run Code Online (Sandbox Code Playgroud)
报告生成器支持的文件格式:https://github.com/danielpalme/ReportGenerator#supported-input-and-output-file-formats
SonarQube 通用测试数据格式: https ://docs.sonarqube.org/latest/analysis/generic-test/
tay*_*onl 19
我认为问题是您正在尝试导入 opencover 测试,但测试采用 cobertura 格式。您可以为您的测试执行此命令:
dotnet test --no-build --collect:"XPlat Code Coverage" -- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=opencover
Run Code Online (Sandbox Code Playgroud)
这很可能会起作用。