You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无单元测试时如何获取dotnet-coverage全量待覆盖代码报告?

无单元测试时如何获取C#项目完整的待覆盖代码覆盖率报告?

问题描述

我正在开发一个C#项目,希望找出需要通过单元测试覆盖的代码行。我执行以下命令来运行测试并将结果上传至SonarQube:

dotnet sonar-scanner-msbuild/SonarScanner.MSBuild.dll begin /k:"projectname" /d:sonar.login="token" /d:sonar.host.url="http://url" /v:0 /d:sonar.cs.vscoveragexml.reportsPaths=coverage.xml

dotnet build path/to/project

dotnet-coverage collect 'dotnet test path/to/project/solution.sln' -f xml  -o 'coverage.xml'

dotnet sonar-scanner-msbuild/SonarScanner.MSBuild.dll end /d:sonar.login="token"

这些命令整体运行正常,但在没有单元测试时出现异常:dotnet-coverage弹出警告信息:

No test is available in /path/to/test/project/bin/Debug/net6.0/testproject.Test.dll. Make sure that test discoverer & executors are registered and platform & framework version settings are appropriate and try again.

No code coverage data available. Profiler was not initialized. Verify that glibc (>=2.27), libxml2 and all .NET dependencies are installed.

这会导致生成的覆盖率报告不完整——没有单元测试时仅统计到27个文件的1956行待覆盖代码,而存在单元测试时能统计到128个文件的3099行待覆盖代码。想咨询:是否有办法在无单元测试时直接获取显示所有待覆盖代码行的完整覆盖率报告?

解决方案

方法1:生成空的VSCoverage格式报告

当没有单元测试时,dotnet-coverage因无法初始化分析器导致报告缺失。可以手动创建一个符合格式的空coverage.xml文件,让SonarQube识别并加载所有已编译代码文件。

空报告核心结构:

<?xml version="1.0" encoding="utf-8"?>
<CoverageSession xmlns="http://schemas.microsoft.com/VisualStudio/TeamTest/2010">
  <Modules>
  </Modules>
</CoverageSession>

调整执行流程:

  1. 执行SonarScanner begin命令
  2. 编译项目
  3. 检查是否存在测试用例:若无则生成上述空coverage.xml;若有则正常执行dotnet-coverage收集
  4. 执行SonarScanner end命令

方法2:使用空OpenCover格式报告

修改SonarScanner begin命令的报告路径参数为/d:sonar.cs.opencover.reportsPaths=coverage.xml,然后创建空的OpenCover格式报告:

<?xml version="1.0" encoding="utf-8"?>
<CoverageSession xmlns="http://schemas.microsoft.com/VisualStudio/TeamTest/2010">
  <Summary numSequencePoints="0" visitedSequencePoints="0" numBranchPoints="0" visitedBranchPoints="0" sequenceCoverage="0" branchCoverage="0" maxCyclomaticComplexity="0" minCyclomaticComplexity="0" />
  <Modules />
</CoverageSession>

此方法同样能让SonarQube扫描所有代码文件,标记出全部待覆盖行。

方法3:跳过覆盖率报告,直接让SonarQube分析编译代码

如果仅需查看所有待覆盖代码行,可跳过覆盖率报告生成步骤,直接让SonarQube分析编译后的程序集。调整后的命令流程:

dotnet sonar-scanner-msbuild/SonarScanner.MSBuild.dll begin /k:"projectname" /d:sonar.login="token" /d:sonar.host.url="http://url" /v:0

dotnet build path/to/project

dotnet sonar-scanner-msbuild/SonarScanner.MSBuild.dll end /d:sonar.login="token"

此时SonarQube会扫描所有已编译代码文件,标记出所有未被测试覆盖的代码行(覆盖率为0%),需确保SonarQube已启用代码覆盖率分析功能。


内容的提问来源于stack exchange,提问作者FarsoFracico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 18:45:06