執行和偵錯測試

MTP 測試專案是以可執行檔的形式建置,可以直接執行(或除錯)。 沒有多餘的運行控制台或命令。 如果發生錯誤,應用程式會以非零結束代碼結束,這在大部分可執行檔中都是典型的。 欲了解更多已知出口代碼,請參見 MTP出口代碼。

小提示

您可以使用 命令列選項來忽略特定 --ignore-exit-code。

你也可以使用 TestingPlatformCommandLineArguments MSBuild 屬性,在專案檔案中設定要套用至特定測試專案的命令列選項。 其中一個常見的使用案例是,測試專案會忽略所有測試,通常會以結束代碼 8 結束(測試會話執行零測試)。 在這種情況下,你可以在 project 檔案中以 PropertyGroup 新增以下內容:

<TestingPlatformCommandLineArguments>$(TestingPlatformCommandLineArguments) --ignore-exit-code 8</TestingPlatformCommandLineArguments>

這很重要

預設情況下,MTP 會收集遙測資料。 欲了解更多資訊及選擇退出選項,請參閱MTP遙測。

備註

從 2.3.0 版本起,已支援 MTP。

若想優雅停靠,請按一次 Ctrl+C 以申請取消。 執行測試即可完成拆卸作業。 要立即終止,請再次按 Ctrl+C 。

用 dotnet publish 發佈測試project並直接執行應用程式,也是另一種執行測試的方式。 例如,執行 ./Contoso.MyTests.exe。 在某些情況下,您也可以使用 dotnet build 來產生可執行檔,但可能會有邊緣案例需要考慮,例如 Native AOT。

使用 dotnet run

可以使用 dotnet run 指令來建立並執行你的測試project。 這是執行測試的最簡單方式,雖然有時最慢。 在本地編輯和執行測試時,使用 dotnet run 很實用,因為它確保測試 project 在需要時能被重建。 dotnet run 也會自動找到目前資料夾裡的專案。

dotnet run --project Contoso.MyTests

如需 dotnet run的詳細資訊,請參閱 dotnet run。

使用 dotnet exec

dotnet exec 或 dotnet 指令用於執行(或執行)已建構的測試project,這是直接執行應用程式的替代方案。 dotnet exec 需要指向已建置測試專案的 DLL 檔案的路徑。

dotnet exec Contoso.MyTests.dll

或

dotnet Contoso.MyTests.dll

備註

提供測試project執行檔的路徑(*.exe)會產生錯誤:

Error:
  An assembly specified in the application dependencies manifest
  (Contoso.MyTests.deps.json) has already been found but with a different
  file extension:
    package: 'Contoso.MyTests', version: '1.0.0'
    path: 'Contoso.MyTests.dll'
    previously found assembly: 'S:\t\Contoso.MyTests\bin\Debug\net10.0\Contoso.MyTests.exe'

如需 dotnet exec的詳細資訊,請參閱 dotnet exec。

使用 dotnet test

從 .NET 10 SDK 開始,dotnet test就有專用的 MTP 模式。 透過 global.json 選取 MTP,或在 .NET 11 預覽版 6 或更新版本中使用 DOTNET_TEST_RUNNER 環境變數。 專用模式支援專案、解決方案、已建置測試模組,以及新版 SDK 中的額外輸入類型。

dotnet test --test-modules Contoso.MyTests.dll

如需了解測試執行器的選擇及如何從 VSTest 相容模式遷移,請參閱「使用 dotnet test 進行測試」。

另請參閱