语言

使用 MSTest UI 自动化 测试 Windows 桌面应用

预览MSTest.Windows.UIAutomation包将 MSTest 生命周期管理与内置Windows UI 自动化 API 集成。 使用它来启动一个未打包的完全受信任桌面应用程序,将其某个窗口识别为 AutomationElement,并在每次测试后停止该应用程序。

该包支持交互式Windows会话中的 Win32、Windows 窗体 和WPF应用程序。 它不提供 MSIX、UWP 或 WinUI 激活、提升进程自动化、无外设桌面、定位符、自动等待、屏幕截图或多窗口对象模型。

Important

此功能需要 MSTest 4.5 预览包和特定于Windows的目标框架。

启用 Windows UI 自动化

使用 MSTest.Sdk,将 EnableWindowsUIAutomation 设置为 true:

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

MSTest.Sdk 添加匹配 MSTest.Windows.UIAutomation 的包。 如果不使用 MSTest.Sdk,请引用与 MSTest 版本匹配的 MSTest.Windows.UIAutomation、MSTest.TestFramework 和 MSTest.TestAdapter。 单独引用兼容的 Microsoft.NET.Test.Sdk 版本,因为它遵循 VSTest 的版本序列。

对于在 Linux 或 macOS 上还原或生成的以 Windows 为目标的项目,请将 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 UI 自动化模式。 该包使用 UIA2 System.Windows.Automation API。 当你需要更丰富的元素交互时,可以在公开的 AutomationElement 之上叠加另一个库,例如 FlaUI。

自定义启动方式和窗口检测

当默认设置不适合你的应用程序时,请重写这些成员:

  • ApplicationShutdownTimeout 控制基类等待正常关闭和强制终止的时间。 默认值为 5 秒。
  • WindowDiscoveryTimeout 控制等待窗口的时间 WindowTest 。 默认值为 10 秒。
  • FindWindow 为使用启动器进程、显示初始屏幕或创建多个顶级窗口的应用程序选择窗口。
  • StopApplication 当所选窗口属于启动的进程 CreateProcessStartInfo 以外的进程时关闭应用程序。

基类在启动和窗口发现期间观察到 TestContext.CancellationToken 。 WindowTest 会在应用程序于窗口出现前退出时,或在发现过程超时时失败。

了解生命周期行为

ApplicationTest 为每个测试调用启动一个应用程序进程。 WindowTest 在进程启动后检测到窗口。 在测试及其清理方法完成后,MSTest 会释放基类资源,通过主窗口请求正常关闭应用程序,并在应用程序未在配置的超时时间内退出时终止进程树。

对于参数化测试和重试,每个调用都会接收其自己的应用程序生命周期。

另请参阅