錄製 UI 自動化 (Xcode 26+)
Xcode 26 的錄製 UI 自動化功能指南,用於透過記錄使用者操作來建立 UI 測試。
三階段工作流程
取自 WWDC 2025-344:
┌─────────────────────────────────────────────────────────────┐
│ UI 自動化工作流程 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. 錄製 ──────► 在模擬器中與 App 互動 │
│ Xcode 捕捉為 Swift 測試程式碼 │
│ │
│ 2. 重播 ──────► 在各種裝置、語言、設定上執行 │
│ 使用測試計劃進行多配置 │
│ │
│ 3. 審查 ──────► 在測試報告中觀看錄製影片 │
│ 透過截圖分析失敗原因 │
│ │
└─────────────────────────────────────────────────────────────┘
階段 1:錄製
開始錄製
- 在 Xcode 中開啟你的 UI 測試檔案
- 將游標置於測試方法內
- 除錯 → 錄製 UI 自動化(或使用錄製按鈕)
- App 會在模擬器中啟動
- 執行動作互動 – Xcode 會產生對應程式碼
- 完成後停止錄製
會錄製的內容
- 點擊按鈕、Cell、控制項
- 輸入文字至文字欄位
- 滑動與滾動
- 手勢(捏合、旋轉)
- 硬體按鈕按下(主畫面、音量)
產生的程式碼範例
// Xcode 從你的操作產生此程式碼
func testLoginFlow() {
let app = XCUIApplication()
app.launch()
// 錄製:點擊 Email 欄位,輸入 Email
app.textFields["Email"].tap()
app.textFields["Email"].typeText("[email protected]")
// 錄製:點擊密碼欄位,輸入密碼
app.secureTextFields["Password"].tap()
app.secureTextFields["Password"].typeText("password123")
// 錄製:點擊登入按鈕
app.buttons["Login"].tap()
}
增強錄製的程式碼
關鍵:錄製的程式碼通常較脆弱。務必增強其穩定性。
1. 加入輔助使用識別碼
錄製的程式碼使用標籤,但會因本地化而失效:
// 錄製(脆弱 - 會因本地化而失效)
app.buttons["Login"].tap()
// 增強(穩定 - 使用識別碼)
app.buttons["loginButton"].tap()
在 App 程式碼中加入識別碼:
// SwiftUI
Button("Login") { ... }
.accessibilityIdentifier("loginButton")
// UIKit
loginButton.accessibilityIdentifier = "loginButton"
2. 加入 waitForExistence
錄製的程式碼假設元素立即存在:
// 錄製(若 App 較慢則可能失敗)
app.buttons["Login"].tap()
// 增強(等待元素)
let loginButton = app.buttons["loginButton"]
XCTAssertTrue(loginButton.waitForExistence(timeout: 5))
loginButton.tap()
3. 加入斷言
錄製的程式碼僅執行動作,不進行驗證:
// 錄製(無驗證)
app.buttons["Login"].tap()
// 增強(含斷言)
app.buttons["loginButton"].tap()
let welcomeLabel = app.staticTexts["welcomeLabel"]
XCTAssertTrue(welcomeLabel.waitForExistence(timeout: 10),
"登入後應顯示歡迎畫面")
4. 使用更簡潔的查詢
錄製的程式碼可能包含過於具體的查詢:
// 錄製(過於具體)
app.tables.cells.element(boundBy: 0).buttons["Action"].tap()
// 增強(更簡潔)
app.buttons["actionButton"].tap()
查詢選擇指南
取自 WWDC 2025-344:
| 情境 | 問題 | 解決方案 |
|---|---|---|
| 本地化字串 | "Login" 會因語言而改變 | 使用 accessibilityIdentifier |
| 深層巢狀檢視 | 長查詢鏈容易中斷 | 使用最短的可能查詢 |
| 動態內容 | Cell 內容會改變 | 使用識別碼或通用查詢 |
| 多個符合項 | 查詢回傳許多元素 | 加入唯一識別碼 |
最佳做法
- 優先使用識別碼而非標籤
- 使用最短的有效查詢
- 避免基於索引的查詢 (
element(boundBy: 0)) - 為動態內容加入識別碼
階段 2:使用測試計劃重播
測試計劃允許在多個設定下執行相同的測試。
建立測試計劃
- 檔案 → 新增 → 檔案 → 測試計劃
- 加入測試目標
- 設定組態
測試計劃結構
{
"configurations": [
{
"name": "iPhone - 英文",
"options": {
"targetForVariableExpansion": {
"containerPath": "container:MyApp.xcodeproj",
"identifier": "MyApp"
},
"language": "en",
"region": "US"
}
},
{
"name": "iPhone - 西班牙文",
"options": {
"language": "es",
"region": "ES"
}
},
{
"name": "iPhone - 深色模式",
"options": {
"userInterfaceStyle": "dark"
}
},
{
"name": "iPad - 橫向",
"options": {
"defaultTestExecutionTimeAllowance": 120,
"testTimeoutsEnabled": true
}
}
],
"defaultOptions": {
"targetForVariableExpansion": {
"containerPath": "container:MyApp.xcodeproj",
"identifier": "MyApp"
}
},
"testTargets": [
{
"target": {
"containerPath": "container:MyApp.xcodeproj",
"identifier": "MyAppUITests",
"name": "MyAppUITests"
}
}
],
"version": 1
}
組態選項
| 選項 | 用途 |
|---|---|
language | 測試本地化 |
region | 測試地區格式 |
userInterfaceStyle | 測試深色/淺色模式 |
targetForVariableExpansion | 用於組態的 App 目標 |
testTimeoutsEnabled | 啟用逾時機制 |
defaultTestExecutionTimeAllowance | 逾時秒數 |
使用測試計劃執行
# 命令列
xcodebuild test \
-scheme "MyApp" \
-testPlan "MyTestPlan" \
-destination "platform=iOS Simulator,name=iPhone 16" \
-resultBundlePath /tmp/results.xcresult
# 在 Xcode 中
# Product → Test Plan → 選擇你的計劃
# 然後按 Cmd+U 執行測試
階段 3:審查
測試報告功能
測試完成後:
- 在報告導覽器檢視測試結果
- 觀看每個測試的錄製影片
- 在失敗點查看截圖
- 分析動作時間軸
啟用附件
在測試計劃或 scheme 中:
"options": {
"systemAttachmentLifetime": "keepAlways",
"userAttachmentLifetime": "keepAlways"
}
擷取自訂截圖
func testCheckout() {
// ... 動作 ...
// 在特定點手動截圖
let screenshot = app.screenshot()
let attachment = XCTAttachment(screenshot: screenshot)
attachment.name = "結帳確認"
attachment.lifetime = .keepAlways
add(attachment)
}
常見模式
登入流程範本
func testLoginWithValidCredentials() throws {
let app = XCUIApplication()
app.launch()
// 導覽至登入
let showLoginButton = app.buttons["showLoginButton"]
XCTAssertTrue(showLoginButton.waitForExistence(timeout: 5))
showLoginButton.tap()
// 輸入憑證
let emailField = app.textFields["emailTextField"]
XCTAssertTrue(emailField.waitForExistence(timeout: 5))
emailField.tap()
emailField.typeText("[email protected]")
let passwordField = app.secureTextFields["passwordTextField"]
passwordField.tap()
passwordField.typeText("password123")
// 提交
app.buttons["loginButton"].tap()
// 驗證成功
let welcomeScreen = app.staticTexts["welcomeLabel"]
XCTAssertTrue(welcomeScreen.waitForExistence(timeout: 10))
}
導覽流程範本
func testNavigateToSettings() throws {
let app = XCUIApplication()
app.launch()
// 開啟分頁列項目
app.tabBars.buttons["設定"].tap()
// 驗證導覽
let settingsTitle = app.navigationBars["設定"]
XCTAssertTrue(settingsTitle.waitForExistence(timeout: 5))
// 更深層導覽
app.tables.cells["帳號"].tap()
XCTAssertTrue(app.navigationBars["帳號"].exists)
}
表單驗證範本
func testFormValidation() throws {
let app = XCUIApplication()
app.launch()
// 提交空表單
app.buttons["submitButton"].tap()
// 驗證錯誤訊息出現
let errorAlert = app.alerts["錯誤"]
XCTAssertTrue(errorAlert.waitForExistence(timeout: 5))
XCTAssertTrue(errorAlert.staticTexts["請填寫所有欄位"].exists)
// 關閉警告
errorAlert.buttons["確定"].tap()
}
疑難排解
錄製無法開始
- 確認你在測試方法中
- 檢查模擬器是否可用
- 確認 App 可建置與執行
- 嘗試重新啟動 Xcode
錄製的程式碼無法運作
- 在互動前加入 waitForExistence
- 檢查輔助使用識別碼是否已設定
- 將查詢簡化至最短形式
- 手動執行 App 以驗證流程是否正常
測試在本地通過,但在 CI 失敗
- 增加逾時時間 以因應 CI 機器較慢的情況
- 為動畫加入明確的等待
- 檢查模擬器設定是否相符
- 在測試設定中停用動畫:
app.launchArguments = ["--disable-animations"]
反模式
不要在 CI 中使用未加工的錄製程式碼
// 不好 - 未加工的錄製程式碼
app.buttons["Login"].tap()
app.textFields["Email"].typeText("[email protected]")
// 好 - 為 CI 增強
let loginButton = app.buttons["loginButton"]
XCTAssertTrue(loginButton.waitForExistence(timeout: 10))
loginButton.tap()
不要硬編碼座標
// 不好 - 錄製的座標
app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()
// 好 - 使用元素查詢
app.buttons["centerButton"].tap()
不要跳過斷言
// 不好 - 僅動作
app.buttons["Login"].tap()
sleep(2) // 希望它成功
// 好 - 驗證結果
app.buttons["loginButton"].tap()
XCTAssertTrue(app.staticTexts["歡迎"].waitForExistence(timeout: 10))
資源
WWDC:2025-344, 2024-10206, 2019-413
文件:/xcode/testing/recording-ui-tests, /xctest/xcuiapplication
技能:axiom-xctest-automation, axiom-ui-testing