共用方式為


在 VSTest 模式中使用 Microsoft.Testing.Platform dotnet test

本文說明在 VSTest 模式 dotnet test中執行時,由 Microsoft.Testing.Platform.MSBuild 所提供的 Microsoft.Testing.Platform 的整合。

在深入探討本文之前,建議您先閱讀 使用 dotnet 測試進行測試,其中說明兩 dotnet test 種模式(VSTest 和 MTP 模式)。

根據預設, dotnet test 會使用 VSTest 來執行測試。 若要在Microsoft.Testing.Platform中啟用dotnet test的支援,您有兩個選項:

  1. dotnet test在 VSTest 模式中使用 ,並在項目檔中指定 <TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport> MSBuild 屬性。
  2. 在 MTP 模式中使用 dotnet test 以在 dotnet test 中提供更多對 MTP 的原生支援,此支援僅從 .NET 10 SDK 開始支援。

這兩個選項都會在 Testing with 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 檔案中新增屬性,例如 EnableMSTestRunnerTestingPlatformDotnetTestSupportTestingPlatformCaptureOutput。 不過,強烈建議您在 Directory.Build.props中設定這些屬性。 如此一來,您就不需要將它新增至每個測試專案檔,也不會有引入未設定這些屬性的新專案的風險,最終導致在一個解決方案中,有些專案使用 VSTest,而有些專案使用 Microsoft.Testing.Platform,這可能會導致運作不正常且屬於不受支援的情境。