首页 > 解决方案 > 在 Azure DevOps 上显示 NUnit 测试代码覆盖率

问题描述

我在 Azure DevOps 上设置了一个新管道,用于构建和运行项目测试。测试是用 NUnit 编写的。

在管道中,我使用任务来VSTest@2运行单元测试,并将.codeCoverageEnabledtrue

最后管道运行,当我进入作业的“代码覆盖率”选项卡时,它允许我下载.codecoverage文件,但它不会在选项卡中显示其内容。我的理解是这应该发生。

我怎样才能解决这个问题 ?

谢谢

标签: c#azure-devopsnunit

解决方案


默认情况下,VSTest 任务的代码覆盖率会输出到一个.codecoverage文件,Azure DevOps 不知道如何解释该文件,仅作为可下载文件提供。您需要使用一些DotNetCoreCLI任务和Coverlet才能在 azure 管道的代码覆盖率选项卡上显示代码覆盖率结果。

因此,如果您使用 .NET CORE,有一种方法可以做到这一点。

第 1 步在您的测试项目中 添加Coverlet.collectornuget 包

第 2 步 更改您azure-pipelines.yml的代码以包括以下代码覆盖率:如果您有CodeCoverage.runsettings文件中的任何设置,您也可以保留它们

- task: DotNetCoreCLI@2
  inputs:
    command: 'test'
    projects: '**/*.Tests/*.csproj'
    arguments: -c $(BuildConfiguration) --collect:"XPlat Code Coverage" -- RunConfiguration.DisableAppDomain=true
    testRunTitle: 'Run Test and collect Coverage' 
  displayName: 'Running tests'

- task: DotNetCoreCLI@2
  inputs:
    command: custom
    custom: tool
    arguments: install --tool-path . dotnet-reportgenerator-globaltool
  displayName: Install ReportGenerator tool

- script: reportgenerator -reports:$(Agent.TempDirectory)/**/coverage.cobertura.xml -targetdir:$(Build.SourcesDirectory)/coverlet/reports -reporttypes:"Cobertura"
  displayName: Create reports

- task: PublishCodeCoverageResults@1
  displayName: 'Publish code coverage'
  inputs:
    codeCoverageTool: Cobertura
    summaryFileLocation: $(Build.SourcesDirectory)/coverlet/reports/Cobertura.xml  

上述代码要注意的另一件事是Report Generator。根据您使用的 .net 核心版本,可能需要获取不同版本的工具。

更多信息也可以在Microsoft Docs上找到


推荐阅读