語言

使用 MSTest 使用者介面自動化 測試 Windows 桌面應用程式

預覽MSTest.Windows.UIAutomation套件整合了 MSTest 生命週期管理與內建的 Windows 使用者介面自動化 API。 用它啟動未封裝的全信任桌面應用程式,找出其一個視窗作為 AutomationElement,並在每次測試後停止此應用程式。

此套件支援在互動式 Windows 工作階段中執行的 Win32、Windows Forms 和 WPF 應用程式。 它不提供 MSIX、UWP 或 WinUI 啟用、提升程序自動化、無頭桌面、定位器、自動等待、截圖或多視窗物件模型。

Important

此功能需要 MSTest 4.5 預覽套件及 Windows 專用的目標框架。

啟用 Windows 使用者介面自動化

使用 MSTest.Sdk,設定 EnableWindowsUIAutomation 為 true:

<Project Sdk="MSTest.Sdk/4.5.0">
  <PropertyGroup>
    <TargetFramework>net8.0-windows</TargetFramework>
    <EnableWindowsUIAutomation>true</EnableWindowsUIAutomation>
  </PropertyGroup>
</Project>

MSTest.Sdk 會新增相應 MSTest.Windows.UIAutomation 的套件。 若未使用 MSTest.Sdk,請參考版本相符的 MSTest.Windows.UIAutomation、MSTest.TestFramework 和 MSTest.TestAdapter。 另外列出相容的 Microsoft.NET.Test.Sdk 版本,因為它遵循 VSTest 的版本系列。

對於針對 Windows 的專案,該專案需還原或建置於 Linux 或 macOS,請設定EnableWindowsTargeting為 true。

選擇一個基礎類別

可從以下類別之一推導出:

  • ApplicationTest 每次測試前開始施用,並在廢棄時停止。 覆寫 CreateProcessStartInfo 以識別執行檔。
  • WindowTest 也會等待視窗,並透過 MainWindow 將其公開。

直接在每個具體測試類別上宣告 STATestClass ,因為 MSTest 測試類別屬性不會繼承:

using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting.Windows.UIAutomation;

[STATestClass]
public sealed class MyAppTests : WindowTest
{
    protected override ProcessStartInfo CreateProcessStartInfo()
        => new(@"C:\MyApp\MyApp.exe");
}
Imports System.Diagnostics
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports Microsoft.VisualStudio.TestTools.UnitTesting.Windows.UIAutomation

<STATestClass>
Public NotInheritable Class MyAppTests
    Inherits WindowTest

    Protected Overrides Function CreateProcessStartInfo() As ProcessStartInfo
        Return New ProcessStartInfo("C:\MyApp\MyApp.exe")
    End Function
End Class

在你的測試方法中用MainWindow來查詢或呼叫Windows 使用者介面自動化模式。 該套件使用 UIA2 System.Windows.Automation API。 當你需要更豐富的元素互動功能時,可以在已公開的 AutomationElement 之上再疊加另一個函式庫,例如 FlaUI。

自訂啟動與視窗偵測

當預設值不符合你的應用程式時,可以覆蓋這些成員:

  • ApplicationShutdownTimeout 控制基底類別在正常關機與強制終止前等待多久。 預設是五秒鐘。
  • WindowDiscoveryTimeout 控制等待窗口的時間 WindowTest 。 預設值是 [10 秒]。
  • FindWindow 為使用啟動程序的應用程式選擇視窗、顯示啟動畫面或建立多個頂層視窗。
  • StopApplication 當所選視窗屬於非啟動程序 CreateProcessStartInfo 的程序時,會關閉該應用程式。

基底類別在啟動及探索視窗期間會觀察 TestContext.CancellationToken。 WindowTest 會在應用程式於視窗出現前結束時,或在探索逾時時失敗。

了解生命週期行為

ApplicationTest 每次測試呼叫啟動一個申請流程。 WindowTest 在程序啟動後偵測到該視窗。 測試及其清理方法結束後,MSTest 會丟棄基底類別,透過主視窗請求優雅關閉,若應用程式未在設定逾時內退出,則終止程序樹。

對於參數化測試與重試,每個呼叫都會獲得自己的應用程式生命週期。

另請參閱