Azure DevOps 构建管道中的 ASP.NET Core Web 应用程序控制器需要 100% 的代码覆盖率

问题描述

在我们的项目中,我们要求所有控制器方法都至少有一个测试。

如果测试失败,我们的构建就会失败,但现在我们正在使用本指南手动检查代码覆盖率:

https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports

基本上这意味着运行两个命令:

dotnet test /p:CollectCoverage=true /p:CoverletoutputFormat=cobertura /p:Coverletoutput="Path\To\TestProject\TestResults\coverage.cobertura.xml"

reportgenerator "-reports:Path\To\TestProject\TestResults\coverage.cobertura.xml" "-targetdir:coveragereport" -reporttypes:Html

注意:如果您运行 dotnet test --collect:"XPlat Code Coverage",您可以获得 coverage.cobertura.xml 文件,但如果您将 msbuild 与 /p:CollectCoverage=true 一起使用,您必须将包 dotnet add package coverlet.msbuild 添加到测试项目中一次。

https://github.com/coverlet-coverage/coverlet/issues/201

然后我们会得到这样的报告:

enter image description here

在这种情况下,我们的线路覆盖率不是很高,但我们的控制器具有 100% 的线路覆盖率。可以检查像 Project.Web.Controllers 这样的特定命名空间是否具有 100% 的行覆盖率。

我们不能使用正常的代码覆盖率结果来使构建失败,因为我们只想在未测试控制器的情况下使构建失败。

https://docs.microsoft.com/en-us/azure/devops/pipelines/test/review-code-coverage-results?view=azure-devops

https://gunnarpeipman.com/azure-devops-check-code-coverage/

https://stackoverflow.com/a/60894835/3850405

有什么办法可以很好地做到这一点,还是我们需要阅读 coverage.cobertura.xml 文件并查看 <class name="Project.Web.Controllers 为例?

解决方法

找到了它的命令!

密钥使用了 /p:Include="[*]Project.Web.Controllers.*" /p:Threshold=100 /p:ThresholdType=line

完成命令:

dotnet test /p:CollectCoverage=true /p:Include="[*]Project.Web.Controllers.*" /p:Threshold=100 /p:ThresholdType=line

https://github.com/coverlet-coverage/coverlet/blob/master/Documentation/MSBuildIntegration.md

通过:

enter image description here

失败:

enter image description here