UI 자동화 녹화 (Xcode 26+)
Xcode 26의 UI 자동화 녹화 기능을 사용하여 사용자 상호 작용을 녹화하여 UI 테스트를 만드는 가이드입니다.
3단계 워크플로우
WWDC 2025-344 참조:
┌─────────────────────────────────────────────────────────────┐
│ UI Automation Workflow │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. RECORD ──────► Interact with app in Simulator │
│ Xcode captures as Swift test code │
│ │
│ 2. REPLAY ──────► Run across devices, languages, configs │
│ Using test plans for multi-config │
│ │
│ 3. REVIEW ──────► Watch video recordings in test report │
│ Analyze failures with screenshots │
│ │
└─────────────────────────────────────────────────────────────┘
1단계: 기록
기록 시작
- Xcode에서 UI 테스트 파일 열기
- 커서를 테스트 메서드 안에 놓기
- Debug → Record UI Automation (또는 기록 버튼 사용)
- 앱이 시뮬레이터에서 실행됨
- 상호 작용 수행 - Xcode가 코드 생성
- 완료되면 기록 중지
기록되는 내용
- 탭 버튼, 셀, 컨트롤
- 텍스트 입력 텍스트 필드
- 스와이프 및 스크롤
- 제스처 (핀치, 회전)
- 하드웨어 버튼 누름 (홈, 볼륨)
생성된 코드 예시
// Xcode가 상호 작용에서 이 코드를 생성합니다.
func testLoginFlow() {
let app = XCUIApplication()
app.launch()
// Recorded: Tap email field, type email
app.textFields["Email"].tap()
app.textFields["Email"].typeText("[email protected]")
// Recorded: Tap password field, type password
app.secureTextFields["Password"].tap()
app.secureTextFields["Password"].typeText("password123")
// Recorded: Tap login button
app.buttons["Login"].tap()
}
기록된 코드 향상
중요: 기록된 코드는 종종 취약합니다. 항상 안정성을 위해 향상시키세요.
1. 접근성 식별자 추가
기록된 코드는 현지화로 인해 깨질 수 있는 레이블을 사용합니다:
// RECORDED (fragile - breaks with localization)
app.buttons["Login"].tap()
// ENHANCED (stable - uses identifier)
app.buttons["loginButton"].tap()
앱 코드에 식별자 추가:
// SwiftUI
Button("Login") { ... }
.accessibilityIdentifier("loginButton")
// UIKit
loginButton.accessibilityIdentifier = "loginButton"
2. waitForExistence 추가
기록된 코드는 요소가 즉시 존재한다고 가정합니다:
// RECORDED (may fail if app is slow)
app.buttons["Login"].tap()
// ENHANCED (waits for element)
let loginButton = app.buttons["loginButton"]
XCTAssertTrue(loginButton.waitForExistence(timeout: 5))
loginButton.tap()
3. 단언문 추가
기록된 코드는 검증 없이 동작만 수행합니다:
// RECORDED (no verification)
app.buttons["Login"].tap()
// ENHANCED (with assertion)
app.buttons["loginButton"].tap()
let welcomeLabel = app.staticTexts["welcomeLabel"]
XCTAssertTrue(welcomeLabel.waitForExistence(timeout: 10),
"로그인 후 환영 화면이 나타나야 합니다")
4. 더 짧은 쿼리 사용
기록된 코드는 지나치게 구체적인 쿼리를 가질 수 있습니다:
// RECORDED (too specific)
app.tables.cells.element(boundBy: 0).buttons["Action"].tap()
// ENHANCED (simpler)
app.buttons["actionButton"].tap()
쿼리 선택 지침
WWDC 2025-344 참조:
| 시나리오 | 문제점 | 해결책 |
|---|---|---|
| 현지화된 문자열 | "Login"이 언어에 따라 변경됨 | accessibilityIdentifier 사용 |
| 깊게 중첩된 뷰 | 긴 쿼리 체인이 쉽게 깨짐 | 가능한 가장 짧은 쿼리 사용 |
| 동적 콘텐츠 | 셀 콘텐츠 변경 | 식별자 또는 일반 쿼리 사용 |
| 여러 일치 항목 | 쿼리가 많은 요소 반환 | 고유 식별자 추가 |
모범 사례
- 레이블보다 식별자 선호
- 작동하는 가장 짧은 쿼리 사용
- 인덱스 기반 쿼리 피하기 (
element(boundBy: 0)) - 동적 콘텐츠에 식별자 추가
2단계: 테스트 계획으로 재생
테스트 계획을 사용하면 여러 구성에서 동일한 테스트를 실행할 수 있습니다.
테스트 계획 만들기
- File → New → File → Test Plan
- 테스트 대상 추가
- 구성 설정
테스트 계획 구조
{
"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 - Dark Mode",
"options": {
"userInterfaceStyle": "dark"
}
},
{
"name": "iPad - Landscape",
"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에서
# Product → Test Plan → 계획 선택
# 그런 다음 Cmd+U로 테스트 실행
3단계: 검토
테스트 보고서 기능
테스트 완료 후:
- Report Navigator에서 테스트 결과 보기
- 각 테스트의 비디오 녹화 시청
- 실패 지점에서 스크린샷 보기
- 작업 타임라인 분석
첨부 파일 활성화
테스트 계획 또는 스킴에서:
"options": {
"systemAttachmentLifetime": "keepAlways",
"userAttachmentLifetime": "keepAlways"
}
사용자 정의 스크린샷 캡처
func testCheckout() {
// ... actions ...
// 특정 지점에서 수동 스크린샷
let screenshot = app.screenshot()
let attachment = XCTAttachment(screenshot: screenshot)
attachment.name = "Checkout Confirmation"
attachment.lifetime = .keepAlways
add(attachment)
}
일반적인 패턴
로그인 흐름 템플릿
func testLoginWithValidCredentials() throws {
let app = XCUIApplication()
app.launch()
// Navigate to login
let showLoginButton = app.buttons["showLoginButton"]
XCTAssertTrue(showLoginButton.waitForExistence(timeout: 5))
showLoginButton.tap()
// Enter credentials
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")
// Submit
app.buttons["loginButton"].tap()
// Verify success
let welcomeScreen = app.staticTexts["welcomeLabel"]
XCTAssertTrue(welcomeScreen.waitForExistence(timeout: 10))
}
탐색 흐름 템플릿
func testNavigateToSettings() throws {
let app = XCUIApplication()
app.launch()
// Open tab bar item
app.tabBars.buttons["Settings"].tap()
// Verify navigation
let settingsTitle = app.navigationBars["Settings"]
XCTAssertTrue(settingsTitle.waitForExistence(timeout: 5))
// Navigate deeper
app.tables.cells["Account"].tap()
XCTAssertTrue(app.navigationBars["Account"].exists)
}
양식 유효성 검사 템플릿
func testFormValidation() throws {
let app = XCUIApplication()
app.launch()
// Submit empty form
app.buttons["submitButton"].tap()
// Verify error appears
let errorAlert = app.alerts["Error"]
XCTAssertTrue(errorAlert.waitForExistence(timeout: 5))
XCTAssertTrue(errorAlert.staticTexts["Please fill all fields"].exists)
// Dismiss alert
errorAlert.buttons["OK"].tap()
}
문제 해결
기록이 시작되지 않음
- 테스트 메서드 안에 있는지 확인
- 시뮬레이터를 사용할 수 있는지 확인
- 앱이 빌드되고 실행되는지 확인
- Xcode 다시 시작 시도
기록된 코드가 작동하지 않음
- 상호 작용 전에 waitForExistence 추가
- 접근성 식별자가 설정되었는지 확인
- 쿼리를 가장 짧은 형태로 간소화
- 앱을 수동으로 실행하여 흐름이 작동하는지 확인
테스트가 로컬에서는 통과하지만 CI에서 실패함
- 느린 CI 머신을 위해 시간 제한 증가
- 애니메이션을 위해 명시적 대기 추가
- 시뮬레이터 구성이 일치하는지 확인
- 테스트 설정에서 애니메이션 비활성화:
app.launchArguments = ["--disable-animations"]
안티 패턴
CI에서 원시 기록 코드를 사용하지 마십시오
// BAD - Raw recorded code
app.buttons["Login"].tap()
app.textFields["Email"].typeText("[email protected]")
// GOOD - Enhanced for CI
let loginButton = app.buttons["loginButton"]
XCTAssertTrue(loginButton.waitForExistence(timeout: 10))
loginButton.tap()
좌표를 하드코딩하지 마십시오
// BAD - Coordinates from recording
app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()
// GOOD - Use element queries
app.buttons["centerButton"].tap()
단언문을 건너뛰지 마십시오
// BAD - Actions only
app.buttons["Login"].tap()
sleep(2) // Hope it works
// GOOD - Verify outcomes
app.buttons["loginButton"].tap()
XCTAssertTrue(app.staticTexts["Welcome"].waitForExistence(timeout: 10))
리소스
WWDC: 2025-344, 2024-10206, 2019-413
문서: /xcode/testing/recording-ui-tests, /xctest/xcuiapplication
스킬: axiom-xctest-automation, axiom-ui-testing