Communitygithub.com

ComeOnOliver/skillshub

用于在 Xcode 26 中设置 UI 测试录制、增强录制测试的稳定性,以及配置多配置回放的测试计划。基于 WWDC 2025-344“录制、回放与审查”。

skillshub 是什么?

此技能面向使用 Xcode 26 和更高版本进行 UI 自动化测试的开发者,特别是在配置测试录制、增强录制代码以及设置 test plan 进行多配置回放时使用。它提供了一套完整的工作流程指南,包含录制(Record)、回放(Replay)和审查(Review)三个阶段,并详细说明了如何利用 accessibilityIdentifier 等最佳实践来提升测试的稳定性和可维护性。该技能还涵盖了常见操作模板、故障排除方法以及反模式建议,帮助开发者避免常见陷阱。支持在 Xcode 内和命令行(xcodebuild)中使用,适用于 iOS Simulator 和各种测试配置。

兼容平台~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/CharlesWiltgen/Axiom/axiom-ui-recording

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

录制 UI 自动化 (Xcode 26+)

使用 Xcode 26 的录制 UI 自动化功能,通过记录用户交互来创建 UI 测试的指南。

三阶段工作流程

源自 WWDC 2025-344:

┌─────────────────────────────────────────────────────────────┐
│                   UI 自动化工作流程                         │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. 录制 ──────► 在模拟器中与应用交互                       │
│                     Xcode 捕获为 Swift 测试代码             │
│                                                             │
│  2. 回放 ──────► 在多种设备、语言、配置上运行               │
│                     使用测试计划进行多配置测试               │
│                                                             │
│  3. 审查 ──────► 在测试报告中观看视频录制                   │
│                     截图分析失败原因                        │
│                                                             │
└─────────────────────────────────────────────────────────────┘

阶段 1: 录制

开始录制

  1. 在 Xcode 中打开你的 UI 测试文件
  2. 将光标置于测试方法内部
  3. 选择 调试 → 录制 UI 自动化 (或使用录制按钮)
  4. 应用在模拟器中启动
  5. 进行操作 - Xcode 会生成代码
  6. 完成后停止录制

录制的内容

  • 点击 按钮、单元格、控件
  • 文本输入 到文本字段
  • 滑动 和滚动
  • 手势 (捏合、旋转)
  • 硬件按键 (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
深层嵌套视图长查询链容易断裂使用尽量短的查询
动态内容单元格内容变化使用标识符或通用查询
多个匹配查询返回多个元素添加唯一标识符

最佳实践

  1. 优先使用标识符而非标签
  2. 使用能生效的最短查询
  3. 避免基于索引的查询 (element(boundBy: 0))
  4. 为动态内容添加标识符

阶段 2: 使用测试计划回放

测试计划允许在多个配置上运行相同的测试。

创建测试计划

  1. 文件 → 新建 → 文件 → 测试计划
  2. 添加测试目标
  3. 配置配置项

测试计划结构

{
  "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: 审查

测试报告功能

测试完成后:

  1. 在报告导航器中查看测试结果
  2. 观看每个测试的视频录制
  3. 在失败点查看截图
  4. 分析操作时间线

启用附件

在测试计划或 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()
}

故障排除

录制未启动

  1. 确保你处于测试方法中
  2. 检查模拟器是否可用
  3. 验证应用能够构建并运行
  4. 尝试重启 Xcode

录制的代码不工作

  1. 在操作前添加 waitForExistence
  2. 检查 accessibilityIdentifier 是否已设置
  3. 将查询简化为最短形式
  4. 手动运行应用 以验证流程正常

测试在本地通过,在 CI 中失败

  1. 为较慢的 CI 机器增加超时时间
  2. 为动画添加显式等待
  3. 检查模拟器配置是否一致
  4. 在测试设置中禁用动画:
    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

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相关技能