You need to enable JavaScript to run this app. Azure DevOps Server 2020中C#代码覆盖率采集发布优化咨询
优惠活动
大模型
产品
解决方案
定价
更多

Azure DevOps Server 2020中C#代码覆盖率采集发布优化咨询

优化方案

最优方案:替换覆盖率采集工具,直接生成目标格式,完全省去转换耗时

该方案可以从根源消除两次格式转换的额外开销,是目前效率最高的解法:

  • 第一步:给测试项目安装Coverlet.MSBuild NuGet包,或者直接使用Coverlet数据收集器(.NET Core 3.1及以上版本默认支持,无需提前装包)
  • 第二步:修改DotNetCoreCLI@2任务的测试命令,替换原有覆盖率采集参数:
dotnet test --no-build -l trx -r TheResultsDir --collect:"XPlat Code Coverage" -- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=cobertura,opencover

该命令执行后会直接生成两种格式的覆盖率文件:

  • opencover格式:可直接提供给SonarQube使用
  • cobertura格式:可直接提供给PublishCodeCoverageResults@1任务使用
  • 第三步:修改SonarQube准备任务配置,将原来的VS覆盖率xml路径配置改为opencover格式路径:
- task: SonarQubePrepare@4
    displayName: Prepare CI SQ Analysis
    inputs:
      SonarQube: SonarQube
      scannerMode: MSBuild
      projectKey: $(SonarQubeProjectKey)
      projectName: $(SonarQubeProjectName)
      projectVersion: $(SonarQubeProjectVersion)
      extraProperties: |
        # 替换原有的vscoveragexml配置为opencover
        sonar.cs.opencover.reportsPaths=$(Common.TestResultsDirectory)\**\coverage.opencover.xml
        sonar.cs.nunit.reportsPaths=$(Common.TestResultsDirectory)\tests\*.TestResult.xml
        sonar.inclusions=**/*.cs
        sonar.branch.name=$(SonarQubeSourceBranch)
        sonar.scm.disabled=true
  • 第四步:修改覆盖率发布任务,直接指向生成的cobertura文件,完全删除原有的两次格式转换步骤:
- task: PublishCodeCoverageResults@1
    displayName: Publish Coverage Results
    inputs:
      codeCoverageTool: Cobertura
      # 直接指向测试步骤生成的cobertura文件
      summaryFileLocation: $(Common.TestResultsDirectory)\**\coverage.cobertura.xml
      failIfCoverageEmpty: true

备选方案:如果无法替换采集工具,优化现有转换流程

如果因为项目历史原因必须使用VS自带的Code Coverage采集,可以通过以下手段大幅压缩转换耗时:

  1. 先合并所有.coverage文件再转换,避免逐个转换的重复开销
    使用CodeCoverage.exe自带的合并命令,先把所有分散的.coverage文件合并为单个文件,再做一次xml转换,比逐个转换效率提升数倍:
# 合并所有.coverage文件
CodeCoverage.exe merge /output:Merged.coverage *.coverage
# 仅转换一次合并后的文件
CodeCoverage.exe analyze /output:CoverageResult.xml Merged.coverage
  1. 优化reportgenerator转换性能
  • 升级到最新版的reportgenerator,新版对大文件的处理性能有至少3倍以上的提升
  • 转换时添加过滤规则,排除系统程序集、第三方依赖包的覆盖率统计,减少需要处理的数据量,同时开启并行处理充分利用硬件性能:
reportgenerator.exe -reports:CoverageResult.xml -targetdir:CoberturaReport -reporttypes:Cobertura -exclude:"[System*]*" -exclude:"[Microsoft*]*" -exclude:"[第三方依赖包名]*" -numberOfReportsParallel:$(Agent.OSCoreCount)

优化后原有2小时以上的转换耗时可以压缩到10分钟以内。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 12:36:03