在
本文介绍 Microsoft.Testing.Platform 在 dotnet test
的 VSTest 模式运行时,由 Microsoft.Testing.Platform.MSBuild 提供的 dotnet test
的集成。
在深入本文之前,建议先阅读 使用 dotnet test 进行测试,其中解释了 dotnet test
的两种模式(VSTest 和 MTP 模式)。
默认情况下, dotnet test
使用 VSTest 运行测试。 若要启用对 Microsoft.Testing.Platform
in dotnet test
的支持,有两个选项:
- 在 VSTest 模式下使用
dotnet test
,并在项目文件中指定<TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport>
MSBuild 属性。 - 从 .NET 10 SDK 开始,在 MTP 模式下使用
dotnet test
,以在dotnet test
中获得对 MTP 的更多本机支持。
在使用 dotnet test 进行测试的文章中详细介绍了这两个选项。
重要
本文余下的部分专门针对 dotnet test
的 VSTest 模式。
谨慎
从 .NET 10 SDK 开始,建议不要在 Microsoft.Testing.Platform 运行时使用 VSTest 模式 dotnet test
。
显示每个测试的失败
默认情况下,测试失败将汇总到 .log 文件中,每个测试项目的单个失败都会报告给 MSBuild。
要显示每个失败测试的错误,请在命令行中指定 -p:TestingPlatformShowTestsFailure=true
,或将 <TestingPlatformShowTestsFailure>true</TestingPlatformShowTestsFailure>
属性添加到项目文件中。
在命令行中:
dotnet test -p:TestingPlatformShowTestsFailure=true
或在项目文件中:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<OutputType>Exe</OutputType>
<EnableMSTestRunner>true</EnableMSTestRunner>
<TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport>
<!-- Add this to your project file. -->
<TestingPlatformShowTestsFailure>true</TestingPlatformShowTestsFailure>
</PropertyGroup>
<!-- ... -->
</Project>
显示完整的平台输出
默认情况下,基础测试可执行文件写入的所有控制台输出都会被捕获并对用户隐藏。 其中包括横幅、版本信息和格式化测试信息。
若要将此信息与 MSBuild 输出一起显示,请使用 <TestingPlatformCaptureOutput>false</TestingPlatformCaptureOutput>
。
此选项不会影响测试框架捕获 Console.WriteLine
写入的用户输出的方式或写入控制台的其他类似方式。
在命令行上:
dotnet test -p:TestingPlatformCaptureOutput=false
或在项目文件中:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<OutputType>Exe</OutputType>
<EnableMSTestRunner>true</EnableMSTestRunner>
<TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport>
<!-- Add this to your project file. -->
<TestingPlatformCaptureOutput>false</TestingPlatformCaptureOutput>
</PropertyGroup>
<!-- ... -->
</Project>
重要
上述所有示例在 csproj 文件中添加 EnableMSTestRunner
、TestingPlatformDotnetTestSupport
和 TestingPlatformCaptureOutput
等属性。 但是,强烈建议在 Directory.Build.props
中设置这些属性。 这样,就不必将其添加到每个测试项目文件中,并且不会冒险引入未设置这些属性的新项目,最终导致解决方案中某些项目是 VSTest,而另一些项目是 Microsoft.Testing.Platform,但这种情况下可能无法正常工作,并且不受支持。