MSTest 运行程序概述

MSTest 运行程序是 VSTest 的轻型可移植替代项,用于在所有上下文(例如,持续集成 (CI) 管道、CLI 和 Visual Studio 测试资源管理器和 VS Code 文本资源管理器等)中运行测试。 MSTest 运行程序直接嵌入到 MSTest 测试项目中,并且不存在任何其他应用依赖项(例如运行测试所需的 vstest.consoledotnet test)。

MSTest 运行程序是开放源代码的,并且是在 Microsoft.Testing.Platform 的基础上构建的。 可以在 microsoft/testfx GitHub 存储库中找到 Microsoft.Testing.Platform 代码。 MSTest 运行程序随附于 MSTest in 3.2.0-preview.23623.1 或更高版本。

在 MSTest 项目中启用 MSTest 运行程序

建议使用 MSTest SDK,因为它可大幅简化项目配置和项目更新,并确保平台(MSTest 运行程序)及其扩展的版本保持一致。

使用 MSTest SDK 时,默认选择使用 MSTest 运行程序。

<Project Sdk="MSTest.Sdk/3.3.1">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

或者,可以通过在项目文件中添加 EnableMSTestRunner 属性并将 OutputType 设置为 Exe 来启用 MSTest 运行程序。 还需要确保使用的是 MSTest 3.2.0-preview.23623.1 或更高版本。

请看看以下示例项目文件:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <!-- Enable the MSTest runner, this is an opt-in feature -->
    <EnableMSTestRunner>true</EnableMSTestRunner>
    <OutputType>Exe</OutputType>

    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>

    <IsPackable>false</IsPackable>
    <IsTestProject>true</IsTestProject>
  </PropertyGroup>

  <ItemGroup>
    <!--
      MSTest meta package is the recommended way to reference MSTest.
      It's equivalent to referencing:
          Microsoft.NET.Test.Sdk
          MSTest.TestAdapter
          MSTest.TestFramework
          MSTest.Analyzers
    -->
    <PackageReference Include="MSTest" Version="3.2.0" />

    <!--
      Coverlet collector isn't compatible with MSTest runner, you can
      either switch to Microsoft CodeCoverage (as shown below),
      or switch to be using coverlet global tool
      https://github.com/coverlet-coverage/coverlet#net-global-tool-guide-suffers-from-possible-known-issue
    -->
    <PackageReference Include="Microsoft.Testing.Extensions.CodeCoverage"
                      Version="17.10.1" />
  </ItemGroup>

</Project>

配置和筛选器

.runsettings

MSTest 运行程序通过命令行选项 --settings 支持 runsettings。 下面的命令显示了示例。

使用 dotnet run

dotnet run --project Contoso.MyTests -- --settings config.runsettings

使用 dotnet exec

dotnet exec Contoso.MyTests.dll --settings config.runsettings

-或-

dotnet Contoso.MyTests.dll --settings config.runsettings

使用可执行文件:

Contoso.MyTests.exe --settings config.runsettings

测试筛选器

可以使用命令行选项 --filter 来提供测试筛选器。 以下命令显示了一些示例。

使用 dotnet run

dotnet run --project Contoso.MyTests -- --filter "FullyQualifiedName~UnitTest1|TestCategory=CategoryA"

使用 dotnet exec

dotnet exec Contoso.MyTests.dll --filter "FullyQualifiedName~UnitTest1|TestCategory=CategoryA"

-或-

dotnet Contoso.MyTests.dll --filter "FullyQualifiedName~UnitTest1|TestCategory=CategoryA"

使用可执行文件:

Contoso.MyTests.exe --filter "FullyQualifiedName~UnitTest1|TestCategory=CategoryA"