当 运行 在 Gitlab CI 管道中时,dotnet-reportgenerator 无法找到任何 coverage.cobertura.xml

dotnet-reportgenerator is not able to find any coverage.cobertura.xml when running inside Gitlab CI pipeline

我想根据本教程为我的 C# 项目生成一个覆盖率报告

https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage

使用以下配置启动 Gitlab CI 管道时

image: mcr.microsoft.com/dotnet/sdk:5.0

stages:
  - build
  - unit-tests

build:
  stage: build
  script:
    - dotnet build --output build
  artifacts:
    paths:
      - build

unit-tests:
  stage: unit-tests
  script:
    - |-
      dotnet test --no-build --output build --collect:"XPlat Code Coverage";
      
      dotnet tool install -g dotnet-reportgenerator-globaltool;

      reportgenerator -reports:'**/coverage.cobertura.xml' -targetdir:'CoverageReports' -reporttypes:'Cobertura';
  artifacts:
    reports:
      cobertura: CoverageReports/Cobertura.xml
  dependencies:
    - build

我收到以下错误

The report file pattern '**/coverage.cobertura.xml' is invalid. No matching files found.

在 运行 执行 reportgenerator 命令之前使用 ls 检查目录时,我可以看到没有匹配的文件(尽管它们应该存在)。

我希望每个测试项目有一个 coverage.cobertura.xml 文件,例如


我目前的解决方案:

看来我必须 运行 重新构建。所以我替换了这一行

dotnet test --no-build --output build --collect:"XPlat Code Coverage";

dotnet test --collect:"XPlat Code Coverage";

现在它工作正常,但额外的构建似乎是多余的,因为我已经创建了一个构建工件...


那么你有什么想法可以改进配置,这样我就不用再构建第二次了吗?

您似乎可以将这两个步骤结合起来,因为 dotnet test 也会触发构建。您可能会在与测试相同的阶段报告构建问题,但两者的响应相似。

image: mcr.microsoft.com/dotnet/sdk:5.0

stages:
  - unit-tests


unit-tests:
  stage: unit-tests
  script:
    - |-
      dotnet test --output build --collect:"XPlat Code Coverage";
      
      dotnet tool install -g dotnet-reportgenerator-globaltool;

      reportgenerator -reports:'../coverage.cobertura.xml' -targetdir:'CoverageReports' -reporttypes:'Cobertura';
  artifacts:
    paths:
      - build
    reports:
      cobertura: CoverageReports/Cobertura.xml

或者: Coverlet 收集器依赖于 CoreCompile。但是,全局工具没有(因为它不是 msbuild 任务)。

image: mcr.microsoft.com/dotnet/sdk:5.0

stages:
  - build
  - unit-tests

build:
  stage: build
  script:
    - dotnet build --output build
  artifacts:
    paths:
      - build

unit-tests:
  stage: unit-tests
  script:
    - |-
      dotnet test --no-build --output build --collect:"XPlat Code Coverage";

      dotnet tool install -g coverlet.console;

      dotnet tool install -g dotnet-reportgenerator-globaltool;

      coverlet /path/to/test-assembly.dll --target "dotnet" --targetargs "test /path/to/test-project --no-build";


      reportgenerator -reports:'../coverage.cobertura.xml' -targetdir:'CoverageReports' -reporttypes:'Cobertura';
  artifacts:
    reports:
      cobertura: CoverageReports/Cobertura.xml
  dependencies:
    - build

Coverlet 的全局工具还支持 --format cobertura 选项,这可能有助于进一步简化这一过程。