共用方式為


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 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。 如需所支援 MSTest 項目的完整清單,請參閱設定 MSTest: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"