使用 Appium 進行 UI 測試

UI 測試透過自動化操作,如點擊按鈕、輸入文字及在頁面間移動,驗證應用程式的使用者介面是否正確運作。 單元 測試 是針對個別方法與類別進行隔離驗證,而 UI 測試則是在真實裝置或模擬器上執行完整應用程式,捕捉只有透過實際使用者互動才會顯現的迴歸行為。

Appium 是一個開源的 UI 測試框架,能支援原生、混合及多個平台的網頁應用程式。 因為 Appium 是從平台層級運作,無論你的應用程式是使用 .NET MAUI 還是平台原生工具,都會以相同方式測試。 Appium 使用平台專用驅動程式將互動傳送到你的應用程式:

平台 Appium 驅動程式 主機作業系統
Android UIAutomator2 Windows、macOS、Linux
iOS XCUITest 僅限 macOS
Mac Catalyst Mac2 僅限 macOS
Windows Windows 僅限 Windows

備註

你能測試什麼取決於你的開發機器。 在 Windows 上,你可以測試 Android 和 Windows 應用程式。 在 macOS 上,你可以測試 Android、iOS 和 Mac 的 Catalyst 應用程式。

小提示

完整工作樣本請參閱GitHub上的Basic Appium NUnit Sample。

先決條件

在撰寫並執行 UI 測試之前,先安裝以下先決條件:

Node.js 與阿皮姆

Appium 建立在 Node.js之上。 安裝 Node.js (建議為 LTS 版本),然後安裝 Appium 和你想測試的平台驅動程式:

# Install Appium
npm install -g appium

# Install platform drivers (install only the ones you need)
appium driver install uiautomator2     # Android
appium driver install xcuitest         # iOS (macOS only)
appium driver install mac2             # Mac Catalyst (macOS only)
appium driver install windows          # Windows

透過終端機執行 appium 來驗證安裝情況。 伺服器應該會啟動並顯示訊息,表示正在監聽 4723 埠。

Windows 應用程式驅動程式(僅限 Windows)

Appium Windows 驅動程式使用 Windows 應用程式驅動程式(WinAppDriver)來自動化Windows應用程式。 下載並安裝 WinAppDriver 版本 1.2.1。

這很重要

請特別使用 WinAppDriver 版本 1.2.1。 其他版本可能無法在 Appium Windows 驅動程式上正常運作。

Android SDK(僅限 Android)

確保 Android SDK 已安裝,且 ANDROID_HOME 環境變數指向其位置。 如果你已經為您的機器設定好 .NET MAUI Android 開發,那應該已經準備就緒。

準備 .NET MAUI 應用程式進行測試

所有你想在測試中互動的 UI 元素,其屬性必須設為唯一的值。 此屬性對應到Appium用來定位元素的平台特定無障礙識別碼。

<Button
    x:Name="CounterBtn"
    AutomationId="CounterBtn"
    Text="Click me"
    SemanticProperties.Hint="Counts the number of times you click"
    Clicked="OnCounterClicked"
    HorizontalOptions="Fill" />

Android 活動註冊

在 Android 上,Appium 需要知道完整限定的活動名稱才能啟動你的應用程式。 為你的[Register]類別新增MainActivity一個屬性,值與你的應用程式套件名稱相符:

[Register("com.companyname.myapp.MainActivity")]
public class MainActivity : MauiAppCompatActivity
{
}

確保Register的屬性值與專案檔案中的ApplicationId及測試設定中的AppActivity能力相符。

建立測試專案

經過驗證的專案結構會使用每個平台的獨立測試專案,並在 NoTargets 專案中使用共享測試程式碼。 這是與官方範例及 .NET MAUI 程式碼庫中所使用的模式相同:

MySolution/
├── MauiApp/                  # Your .NET MAUI app
├── UITests.Shared/           # Shared test code (NoTargets project)
├── UITests.Android/          # Android-specific setup
├── UITests.iOS/              # iOS-specific setup
├── UITests.Windows/          # Windows-specific setup
└── UITests.macOS/            # macOS-specific setup

每個平台專案透過連結至共享專案中的檔案來編譯共享程式碼。 這表示 Shared 專案中的所有測試都能在你測試的每個平台上執行。 Shared 專案本身無法直接執行。 務必執行平台專屬的測試專案。

這很重要

在所有測試專案中保持命名空間不變(例如, UITests)。 NUnit 的 [SetUpFixture] 屬性會執行同一命名空間內所有測試燈具的設定方法。 如果命名空間不匹配,Appium 驅動程式在執行測試時不會被初始化。

平台測試專案 NuGet 套件

每個平台專屬測試專案都需要以下 NuGet 套件:

<ItemGroup>
    <PackageReference Include="Appium.WebDriver" Version="8.0.0" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
    <PackageReference Include="NUnit" Version="3.14.0" />
    <PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
</ItemGroup>

小提示

你不必從零開始建立測試專案,而是可以安裝社群維護的範本,為你搭建完整的專案結構。 欲了解更多資訊,請參閱 Template.Maui.UITesting GitHub 資料庫。

寫一個基礎測試類別

在 Shared 專案中建立一個 BaseTest.cs 檔案。 此基底類別提供 Appium 驅動程式及一個輔助方法,處理 Windows 與其他平台元素位置差異:

using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Windows;

namespace UITests;

public abstract class BaseTest
{
    protected AppiumDriver App => AppiumSetup.App;

    protected AppiumElement FindUIElement(string id)
    {
        if (App is WindowsDriver)
        {
            return App.FindElement(MobileBy.AccessibilityId(id));
        }

        return App.FindElement(MobileBy.Id(id));
    }
}

在Windows上,AutomationId 可透過 MobileBy.AccessibilityId 存取。 在 Android、iOS 和 macOS 上,請使用 MobileBy.Id。

啟動 Appium 伺服器

Appium 伺服器必須在你執行測試前已經運行中。 最簡單的方法是從終端機手動啟動:

appium

預設情況下,伺服器會在 http://127.0.0.1:4723 上啟動。 你做測試時讓它繼續運轉。

以程式化方式啟動伺服器(可選)

為了讓你的測試套件自成一體,你可以在測試執行中啟動或關閉 Appium 伺服器。 在 Shared 專案中建立 AppiumServerHelper.cs 檔案:

using OpenQA.Selenium.Appium.Service;

namespace UITests;

public static class AppiumServerHelper
{
    private static AppiumLocalService? _appiumLocalService;

    public const string DefaultHostAddress = "127.0.0.1";
    public const int DefaultHostPort = 4723;

    public static void StartAppiumLocalServer(
        string host = DefaultHostAddress,
        int port = DefaultHostPort)
    {
        if (_appiumLocalService is not null)
            return;

        var builder = new AppiumServiceBuilder()
            .WithIPAddress(host)
            .UsingPort(port);

        _appiumLocalService = builder.Build();
        _appiumLocalService.Start();
    }

    public static void DisposeAppiumLocalServer()
    {
        _appiumLocalService?.Dispose();
    }
}

為每個平台配置 Appium

每個平台專案都包含一個 AppiumSetup.cs 檔案,負責配置 Appium 驅動程式並提供平台專屬選項。 此類別使用 NUnit [SetUpFixture] 屬性在所有測試執行前初始化一次驅動程式。

Android

using NUnit.Framework;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Appium.Enums;

namespace UITests;

[SetUpFixture]
public class AppiumSetup
{
    private static AppiumDriver? driver;

    public static AppiumDriver App => driver
        ?? throw new NullReferenceException("AppiumDriver is null");

    [OneTimeSetUp]
    public void RunBeforeAnyTests()
    {
        AppiumServerHelper.StartAppiumLocalServer();

        var androidOptions = new AppiumOptions
        {
            AutomationName = "UIAutomator2",
            PlatformName = "Android",
        };

        // For debug builds, use NoReset to preserve Fast Deployment libraries
        androidOptions.AddAdditionalAppiumOption(
            MobileCapabilityType.NoReset, "true");
        androidOptions.AddAdditionalAppiumOption(
            AndroidMobileCapabilityType.AppPackage,
            "com.companyname.myapp");
        androidOptions.AddAdditionalAppiumOption(
            AndroidMobileCapabilityType.AppActivity,
            "com.companyname.myapp.MainActivity");

        driver = new AndroidDriver(androidOptions);
    }

    [OneTimeTearDown]
    public void RunAfterAnyTests()
    {
        driver?.Quit();
        AppiumServerHelper.DisposeAppiumLocalServer();
    }
}

備註

在 Android 上進行除錯建置時,設 NoReset 為 true。 除錯建置使用 Fast Deployment,而 Appium 預設的重置行為會刪除 Fast Deployment 所需的函式庫。 對於發佈版本,您可以改為將 App 屬性設置為簽署 .apk 檔案的完整路徑。

iOS

using NUnit.Framework;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.iOS;

namespace UITests;

[SetUpFixture]
public class AppiumSetup
{
    private static AppiumDriver? driver;

    public static AppiumDriver App => driver
        ?? throw new NullReferenceException("AppiumDriver is null");

    [OneTimeSetUp]
    public void RunBeforeAnyTests()
    {
        AppiumServerHelper.StartAppiumLocalServer();

        var iOSOptions = new AppiumOptions
        {
            AutomationName = "XCUITest",
            PlatformName = "iOS",
            PlatformVersion = "17.0",
            DeviceName = "iPhone 15 Pro",
            App = "com.companyname.myapp",
        };

        driver = new IOSDriver(iOSOptions);
    }

    [OneTimeTearDown]
    public void RunAfterAnyTests()
    {
        driver?.Quit();
        AppiumServerHelper.DisposeAppiumLocalServer();
    }
}

Windows

using NUnit.Framework;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Windows;

namespace UITests;

[SetUpFixture]
public class AppiumSetup
{
    private static AppiumDriver? driver;

    public static AppiumDriver App => driver
        ?? throw new NullReferenceException("AppiumDriver is null");

    [OneTimeSetUp]
    public void RunBeforeAnyTests()
    {
        AppiumServerHelper.StartAppiumLocalServer();

        var windowsOptions = new AppiumOptions
        {
            AutomationName = "windows",
            PlatformName = "Windows",
            App = "com.companyname.myapp_9zz4h110yvjzm!App",
        };

        driver = new WindowsDriver(windowsOptions);
    }

    [OneTimeTearDown]
    public void RunAfterAnyTests()
    {
        driver?.Quit();
        AppiumServerHelper.DisposeAppiumLocalServer();
    }
}

Mac Catalyst

using NUnit.Framework;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Enums;
using OpenQA.Selenium.Appium.Mac;

namespace UITests;

[SetUpFixture]
public class AppiumSetup
{
    private static AppiumDriver? driver;

    public static AppiumDriver App => driver
        ?? throw new NullReferenceException("AppiumDriver is null");

    [OneTimeSetUp]
    public void RunBeforeAnyTests()
    {
        AppiumServerHelper.StartAppiumLocalServer();

        var macOptions = new AppiumOptions
        {
            AutomationName = "mac2",
            PlatformName = "Mac",
            App = "/path/to/MyApp/bin/Debug/net10.0-maccatalyst/maccatalyst-x64/MyApp.app",
        };

        macOptions.AddAdditionalAppiumOption(
            IOSMobileCapabilityType.BundleId,
            "com.companyname.myapp");

        driver = new MacDriver(macOptions);
    }

    [OneTimeTearDown]
    public void RunAfterAnyTests()
    {
        driver?.Quit();
        AppiumServerHelper.DisposeAppiumLocalServer();
    }
}

這很重要

Mac Catalyst 必須設定 BundleId 選項。 沒有它,Appium 會自動化 Finder,而不是你的應用程式。

撰寫 UI 測試

在 Shared 專案中加入測試類別,讓它們能在所有平台上運行。 每個測試類別應繼承自BaseTest。 以下範例測試預設 .NET MAUI 範本中的計數器按鈕:

using NUnit.Framework;

namespace UITests;

public class MainPageTests : BaseTest
{
    [Test]
    public void AppLaunches()
    {
        App.GetScreenshot().SaveAsFile($"{nameof(AppLaunches)}.png");
    }

    [Test]
    public void ClickCounterTest()
    {
        // Arrange
        var element = FindUIElement("CounterBtn");

        // Act
        element.Click();
        Task.Delay(500).Wait();

        // Assert
        App.GetScreenshot().SaveAsFile($"{nameof(ClickCounterTest)}.png");
        Assert.That(element.Text, Is.EqualTo("Clicked 1 time"));
    }
}

此方法根據 AutomationId 值來定位控制項。 你也可以使用其他選擇器:

Selector 方法 Notes
自動化識別碼 MobileBy.Id() 或 MobileBy.AccessibilityId() 優先。 用 FindUIElement 輔助工具抽象平台差異。
XPath MobileBy.XPath() 雖然較慢,但對複雜查詢很有用。
類別名稱 MobileBy.ClassName() 依據其原生類別名稱尋找元素。

小提示

設定 AutomationId 在你想測試的每個元素上。 這是在所有平台上尋找元素最可靠且效能最高的方法。

執行UI測試

在進行測試前,請確保:

  • .NET MAUI 應用程式部署至目標裝置或模擬器。
  • 對於 Android 來說,啟動模擬器或連接實體裝置。
  • 在 iOS 上,模擬器正在運行或裝置已配置。
  • 對於 Windows 來說,應用程式是先安裝的(例如,先從 Visual Studio 執行)。
  • 對於 macOS,該 .app 套件已建置並可在指定的 AppiumSetup.cs 路徑下取得。

可使用 Test Explorer,或從命令列從 Visual Studio 執行測試:

dotnet test UITests.Android/UITests.Android.csproj

用你想測試的平台取代專案路徑。

另請參閱