录制 UI 自动化 (Xcode 26+)
使用 Xcode 26 的录制 UI 自动化功能,通过记录用户交互来创建 UI 测试的指南。
三阶段工作流程
源自 WWDC 2025-344:
┌─────────────────────────────────────────────────────────────┐
│ UI 自动化工作流程 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. 录制 ──────► 在模拟器中与应用交互 │
│ Xcode 捕获为 Swift 测试代码 │
│ │
│ 2. 回放 ──────► 在多种设备、语言、配置上运行 │
│ 使用测试计划进行多配置测试 │
│ │
│ 3. 审查 ──────► 在测试报告中观看视频录制 │
│ 截图分析失败原因 │
│ │
└─────────────────────────────────────────────────────────────┘
阶段 1: 录制
开始录制
- 在 Xcode 中打开你的 UI 测试文件
- 将光标置于测试方法内部
- 选择 调试 → 录制 UI 自动化 (或使用录制按钮)
- 应用在模拟器中启动
- 进行操作 - Xcode 会生成代码
- 完成后停止录制
录制的内容
- 点击 按钮、单元格、控件
- 文本输入 到文本字段
- 滑动 和滚动
- 手势 (捏合、旋转)
- 硬件按键 (Home、音量)
生成的代码示例
// Xcode 根据你的操作生成此代码
func testLoginFlow() {
let app = XCUIApplication()
app.launch()
// 录制的: 点击邮件字段,输入邮件
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()
在你的应用代码中添加标识符:
// SwiftUI
Button("登录") { ... }
.accessibilityIdentifier("loginButton")
// UIKit
loginButton.accessibilityIdentifier = "loginButton"
2. 添加 waitForExistence
录制的代码假定元素会立即存在:
// 录制的 (应用慢时可能失败)
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 |
| 深层嵌套视图 | 长查询链容易断裂 | 使用尽量短的查询 |
| 动态内容 | 单元格内容变化 | 使用标识符或通用查询 |
| 多个匹配 | 查询返回多个元素 | 添加唯一标识符 |
最佳实践
- 优先使用标识符而非标签
- 使用能生效的最短查询
- 避免基于索引的查询 (
element(boundBy: 0)) - 为动态内容添加标识符
阶段 2: 使用测试计划回放
测试计划允许在多个配置上运行相同的测试。
创建测试计划
- 文件 → 新建 → 文件 → 测试计划
- 添加测试目标
- 配置配置项
测试计划结构
{
"configurations": [
{
"name": "iPhone - English",
"options": {
"targetForVariableExpansion": {
"containerPath": "container:MyApp.xcodeproj",
"identifier": "MyApp"
},
"language": "en",
"region": "US"
}
},
{
"name": "iPhone - Spanish",
"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 | 用于配置的应用目标 |
testTimeoutsEnabled | 启用超时强制检查 |
defaultTestExecutionTimeAllowance | 超时时间 (秒) |
使用测试计划运行
# 命令行
xcodebuild test \
-scheme "MyApp" \
-testPlan "MyTestPlan" \
-destination "platform=iOS Simulator,name=iPhone 16" \
-resultBundlePath /tmp/results.xcresult
# 在 Xcode 中
# 产品 → 测试计划 → 选择计划
# 然后按 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()
}
故障排除
录制未启动
- 确保你处于测试方法中
- 检查模拟器是否可用
- 验证应用能够构建并运行
- 尝试重启 Xcode
录制的代码不工作
- 在操作前添加 waitForExistence
- 检查 accessibilityIdentifier 是否已设置
- 将查询简化为最短形式
- 手动运行应用 以验证流程正常
测试在本地通过,在 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