如果未达到阈值,C# Msbuild 代码覆盖率将硬停止

C# Msbuild code coverage hard halt if not met threshold

我们有一个包含多个项目的 c# 解决方案。项目使用msbuild进行打包,运行Nunit进行单元测试。我们目前没有的是为每个项目定义代码覆盖率阈值,并且如果代码覆盖率低于阈值限制则使 msbuild 失败。这在 java 项目中开箱即用,使用 maven 和 cobertura 作为插件。 点网世界中的任何此类工具。

我们正在使用 - Visual Studio 2017 专业 - MSbuild 15.3.409.57025 - Resharper 终极版 2017.2 - 点网框架 4.6.2 - 尼尼特 2.5.7

如果您使用的是 ReSharper,则可以使用 DotCover 作为代码覆盖工具。此工具可以生成一份报告,然后可以使用构建目标进行分析以使构建失败。

<Target Name="FailBuildOnLowCoverage">

    <!-- $(DotCoverResult) is the text of the report that you obtained by reading the report file -->

    <PropertyGroup>
      <CodeCoverageValue>$([System.Text.RegularExpressions.Regex]::Match($(DotCoverResult), '(?&lt;="Total",)(.*?)(?=[,])'))</CodeCoverageValue>
      <CodeCoverageValue Condition="'$(CodeCoverageValue)' == ''">0</CodeCoverageValue>
    </PropertyGroup>


<Message Condition="'$(CodeCoverageValue)' &lt; '30'" Text="Code coverage is less than 30%!

░░░░░░░░░░░█████████████
░░░░░░░░░███░███░░░░░░██
███░░░░░██░░░░██░██████████
████████░░░░░░████░░░░░░░██
████░░░░░░░░░░██░░██████████
████░░░░░░░░░░░███░░░░░░░░░██
████░░░░░░░░░░░██░░██████████
████░░░░░░░░░░░░████░░░░░░░░█
████░░░░░░░░░░░░░███░░████░░█
█████████░░░░░░░░░░████░░░░░█
███░░░░░██░░░░░░░░░░░░░█████
░░░░░░░░░███░░░░░░░██████
░░░░░░░░░░░██░░░░░░██
░░░░░░░░░░░░███░░░░░██
░░░░░░░░░░░░░░██░░░░██
░░░░░░░░░░░░░░░███░░░██
░░░░░░░░░░░░░░░░░██░░░█
░░░░░░░░░░░░░░░░░░█░░░█
░░░░░░░░░░░░░░░░░░██░██
░░░░░░░░░░░░░░░░░░░███
" />