排除 ef core 迁移文件的代码覆盖率

las*_*2d2 5 c# nunit code-coverage entity-framework-core coverlet

我想从代码覆盖率计算中排除所有自动生成的迁移文件。我无法更改dotnet test构建管道中的命令,所以我想我唯一的朋友就是属性[ExcludeFromCodeCoverage]

棘手的部分是,每次添加新的迁移时,我都需要手动检查所有生成的文件,并确保我[ExcludeFromCodeCoverage]在所有生成的类上都有属性,这很好,但我想知道是否有更好的解决方案,我可以一次性完成全部?

迁移文件

[ExcludeFromCodeCoverage] // Manually added everytime
partial class Initial : Migration
Run Code Online (Sandbox Code Playgroud)

和 ModelSnapshot 文件

[ExcludeFromCodeCoverage] // This gets removed everytime snapshot is updated
[DbContext(typeof(MyContext))]
partial class MyContextModelSnapshot : ModelSnapshot
Run Code Online (Sandbox Code Playgroud)

对于快照文件,由于类名始终相同,我可以创建一个单独的文件MyContextModelSnapshot.CodeCoverage.cs文件并将属性放在部分类上,但是迁移文件有解决方案吗?

coverlet.msbuild如果重要的话我正在合作。

Ala*_*dez 7

首先确保问题不是.runsettings 文件的检测。

显然对于dotnet test相对路径“./”不起作用。所以你应该使用完整路径(我无法让它与此一起工作)

[参考这篇文章] https://alexanderontesting.com/2019/03/12/applying-a-runsettings-file-file-from-the-command-line-in-net-core/

但如果你用的是被单。

您可以使用参数exceptByFile

如果我尝试使用 .runsettings 文件(相对路径)运行

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <DataCollectionRunSettings>
    <DataCollectors>
      <DataCollector friendlyName="XPlat code coverage">
        <Configuration>
          <Format>cobertura</Format>                              
          <ExcludeByFile>"**/*Migrations/*.cs"</ExcludeByFile>       
        </Configuration>
      </DataCollector>
    </DataCollectors>
  </DataCollectionRunSettings>
</RunSettings>
Run Code Online (Sandbox Code Playgroud)

通过 -s 参数使用 .runsettings 文件

dotnet test /p:CollectCoverage=true -s .\coverlet.runsettings

结果不是预期的(由于迁移文件导致 1% 的行覆盖率)

+---------+------+--------+--------+
|         | Line | Branch | Method |
+---------+------+--------+--------+
| Total   | 1.3% | 25.03% | 23.93% |
+---------+------+--------+--------+
| Average | 1.3% | 25.03% | 23.93% |
+---------+------+--------+--------+
Run Code Online (Sandbox Code Playgroud)

但是如果我从命令行添加参数(像这样)

 dotnet test /p:CollectCoverage=true /p:ExcludeByFile="**/*Migrations/*.cs"
Run Code Online (Sandbox Code Playgroud)

结果是预期的(38%线路覆盖率)

+---------+--------+--------+--------+
|         | Line   | Branch | Method |
+---------+--------+--------+--------+
| Total   | 38.83% | 25.03% | 27.24% |
+---------+--------+--------+--------+
| Average | 38.83% | 25.03% | 27.24% |
+---------+--------+--------+--------+
Run Code Online (Sandbox Code Playgroud)

可用的参数取决于您的测试工具(有关被套的信息,您可以参考):

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

希望这有帮助