首页 > 解决方案 > 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

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

在此处输入图像描述

在这种情况下,我们的线路覆盖率不是很好,但我们的控制器有 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例如?

标签: c#azure-devopscode-coveragexunitcoverlet

解决方案


找到了它的命令!

关键是使用/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

经过:

在此处输入图像描述

失败:

在此处输入图像描述


推荐阅读