小窍门
使用 Microsoft.Testing.Platform.MSBuild (由 MSTest、NUnit 和 xUnit 运行程序以可传递方式包含)时,安装其 NuGet 包时,会自动注册代码覆盖率扩展 ,无需更改代码。
可以使用代码覆盖率功能来确定正在由编码的测试(例如单元测试)进行测试的项目代码的比例。 若要有效防止 Bug,测试应作用于或覆盖你的大部分代码。
Microsoft 代码覆盖率
Microsoft 代码覆盖分析可用于托管代码(CLR)和非托管代码(原生)。 支持静态和动态仪器。 此扩展需要 Microsoft.Testing.Extensions.CodeCoverage NuGet 包。
注释
默认情况下,扩展中禁用非托管(本机)代码覆盖率。 根据需要使用标志 EnableStaticNativeInstrumentation 和 EnableDynamicNativeInstrumentation 启用它。
有关非托管代码覆盖率的详细信息,请参阅静态和动态本机检测。
重要
该包采用 Microsoft .NET 库闭源免费使用许可模型。
有关 Microsoft 代码覆盖率的详细信息,请参阅其 GitHub 页面。
选项
| Option | Description |
|---|---|
--coverage |
使用 dotnet-coverage 工具收集代码覆盖率。 |
--coverage-output |
生成的覆盖文件的名称或路径。 默认情况下,该文件名为TestResults/<guid>.coverage。 |
--coverage-output-format |
输出文件格式。 支持的值为:coverage、xml 和 cobertura。 默认值为 coverage。 |
--coverage-settings |
XML 代码覆盖率设置。 |
注释
Microsoft.Testing.Extensions.CodeCoverage 中的默认值为IncludeTestAssembly,而在 VSTest 中曾是false。 这意味着默认排除测试项目。 有关详细信息,请参阅 代码覆盖率配置。
版本兼容性
下表显示了不同版本的 Microsoft.Testing.Extensions.CodeCoverage 与 Microsoft.Testing.Platform 之间的兼容性:
| Microsoft.Testing.Extensions.CodeCoverage | Microsoft.Testing.Platform |
|---|---|
| 18.1.x | 2.0.x |
| 18.0.x | 1.8.x |
| 17.14.x | 1.6.2 |
注释
为了获得最佳兼容性和最新功能,建议同时使用这两个包的最新版本。
被单
Coverlet Microsoft测试平台集成(coverlet.MTP)是Microsoft.Testing.Platform的本机扩展,提供coverlet.collector 功能。
将 coverlet.MTP NuGet 包添加到测试项目:
dotnet add package coverlet.MTP
若要收集代码覆盖率,请使用 --coverlet 标志运行测试:
dotnet test --coverlet
或者使用--coverlet标志运行你的测试可执行文件:
dotnet exec <test-assembly.dll> --coverlet
测试运行后, coverage.json 会在当前目录中生成包含结果的文件。
选项
| Option | Description |
|---|---|
--coverlet |
启用代码覆盖率数据收集。 |
--coverlet-output-format <format> |
覆盖报表的输出格式。 支持的格式:json、、lcovopencover、cobertura和teamcity。 多次指定以包含多种格式。 |
--coverlet-include <filter> |
包括与筛选器匹配的程序集,例如 [Assembly]Type。 指定多次添加更多筛选器。 |
--coverlet-include-directory <path> |
包含用于源文件的附加目录。 指定多次以添加更多目录。 |
--coverlet-exclude <filter> |
排除与筛选器匹配的程序集,例如 [Assembly]Type。 指定多次添加更多筛选器。 |
--coverlet-exclude-by-file <pattern> |
排除与 glob 模式匹配的源文件。 指定多次以添加更多模式。 |
--coverlet-exclude-by-attribute <attribute> |
排除使用特定属性修饰的方法或类。 指定多次以添加更多属性。 |
--coverlet-include-test-assembly |
在覆盖率报告中包括测试程序集。 |
--coverlet-single-hit |
将代码中每个位置的命中次数限制为一个。 |
--coverlet-skip-auto-props |
跳过覆盖区中自动实现的属性。 |
--coverlet-does-not-return-attribute <attribute> |
将方法标记为不返回的属性。 指定多次以添加更多属性。 |
--coverlet-exclude-assemblies-without-sources <value> |
排除没有源代码的程序集。 值: MissingAll、 MissingAny和 None。 |
有关详细信息,请参阅 coverlet。MTP 文档。