Warum dedizierte Hardware für Tests?
UI-Tests auf gemeinsam genutzten oder lokalen Maschinen führen zu Instabilität, Inkonsistenz und Engpässen. Ein dedizierter Mac-Server löst diese Probleme.
Konsistente Ergebnisse
Keine anderen Prozesse konkurrieren um CPU oder RAM. Tests laufen jedes Mal in einer sauberen, kontrollierten Umgebung ab, wodurch instabile Testfehler durch Ressourcenkonkurrenz vermieden werden.
Parallele Ausführung
Führen Sie Tests über mehrere iOS-Simulator-Instanzen gleichzeitig aus. Die 14 Kerne des M4 Pro bewältigen 4-6 parallele Simulator-Instanzen ohne Leistungseinbußen.
Verfügbarkeit rund um die Uhr
Tests laufen jederzeit -- nächtliche Regressions-Suites, Validierung nach dem Merge oder auf Abruf. Der Server ist immer bereit, kein Entwickler-Laptop erforderlich.
XCTest auf einem dedizierten Mac
XCTest ist Apples integriertes Test-Framework, das mit Xcode geliefert wird. XCUITest erweitert es für UI-Tests. Beide laufen nativ und erfordern keine zusätzliche Einrichtung über Xcode hinaus.
XCTest über die Befehlszeile ausführen
# Run all unit tests xcodebuild test \ -workspace MyApp.xcworkspace \ -scheme MyApp \ -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.2' \ -resultBundlePath ./TestResults/UnitTests.xcresult # Run only UI tests xcodebuild test \ -workspace MyApp.xcworkspace \ -scheme MyAppUITests \ -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.2' \ -resultBundlePath ./TestResults/UITests.xcresult # Run a specific test class xcodebuild test \ -workspace MyApp.xcworkspace \ -scheme MyApp \ -destination 'platform=iOS Simulator,name=iPhone 16' \ -only-testing:MyAppTests/LoginTests # Run a specific test method xcodebuild test \ -workspace MyApp.xcworkspace \ -scheme MyApp \ -destination 'platform=iOS Simulator,name=iPhone 16' \ -only-testing:MyAppTests/LoginTests/testSuccessfulLogin
Tests auf mehreren Zielen
# Test on multiple iPhone models simultaneously xcodebuild test \ -workspace MyApp.xcworkspace \ -scheme MyApp \ -destination 'platform=iOS Simulator,name=iPhone 16' \ -destination 'platform=iOS Simulator,name=iPhone 16 Pro Max' \ -destination 'platform=iOS Simulator,name=iPhone SE (3rd generation)' \ -destination 'platform=iOS Simulator,name=iPad Pro 13-inch (M4)' \ -resultBundlePath ./TestResults/MultiDevice.xcresult # List all available destinations xcodebuild -showdestinations \ -workspace MyApp.xcworkspace \ -scheme MyApp
Ergebnis-Bundles und Screenshots
# Extract test results summary xcrun xcresulttool get --path ./TestResults/UITests.xcresult \ --format json # Export test attachments (screenshots, videos) xcrun xcresulttool export \ --path ./TestResults/UITests.xcresult \ --output-path ./TestArtifacts \ --type attachments # Get human-readable test summary xcrun xcresulttool get --path ./TestResults/UITests.xcresult \ --format json | python3 -m json.tool
Appium-Einrichtung für iOS
Appium ist ein Open-Source-Automatisierungs-Framework, mit dem Sie Tests in jeder Sprache (Python, JavaScript, Java usw.) schreiben und gegen iOS-Apps auf Simulatoren oder Geräten ausführen können. Es nutzt Apples XCUITest-Treiber im Hintergrund.
Appium auf Ihrem Mac-Server installieren
# Install Node.js via Homebrew brew install node # Install Appium 2.x globally npm install -g appium # Install the XCUITest driver for iOS appium driver install xcuitest # Verify installation appium --version appium driver list --installed # Install appium-doctor to check dependencies npm install -g appium-doctor appium-doctor --ios # Start Appium server appium server --address 127.0.0.1 --port 4723
Desired Capabilities konfigurieren
# Example capabilities (JSON format for Appium 2.x)
{
"platformName": "iOS",
"appium:automationName": "XCUITest",
"appium:deviceName": "iPhone 16",
"appium:platformVersion": "18.2",
"appium:app": "/path/to/MyApp.app",
"appium:noReset": false,
"appium:wdaStartupRetries": 3,
"appium:wdaStartupRetryInterval": 20000,
"appium:simulatorStartupTimeout": 120000
}
Beispiel für einen Appium-Test (Python)
# Install Appium Python client
# pip install Appium-Python-Client
from appium import webdriver
from appium.options.ios import XCUITestOptions
from appium.webdriver.common.appiumby import AppiumBy
# Configure options
options = XCUITestOptions()
options.platform_name = "iOS"
options.device_name = "iPhone 16"
options.platform_version = "18.2"
options.app = "/path/to/MyApp.app"
# Connect to Appium server
driver = webdriver.Remote(
command_executor="http://127.0.0.1:4723",
options=options
)
try:
# Wait for app to load
driver.implicitly_wait(10)
# Find and tap login button
login_button = driver.find_element(
AppiumBy.ACCESSIBILITY_ID, "loginButton"
)
login_button.click()
# Enter username
username_field = driver.find_element(
AppiumBy.ACCESSIBILITY_ID, "usernameField"
)
username_field.send_keys("testuser@example.com")
# Enter password
password_field = driver.find_element(
AppiumBy.ACCESSIBILITY_ID, "passwordField"
)
password_field.send_keys("password123")
# Submit login
submit_button = driver.find_element(
AppiumBy.ACCESSIBILITY_ID, "submitButton"
)
submit_button.click()
# Verify welcome screen
welcome_label = driver.find_element(
AppiumBy.ACCESSIBILITY_ID, "welcomeLabel"
)
assert "Welcome" in welcome_label.text
print("Test PASSED: Login successful")
finally:
driver.quit()
Beispiel für einen Appium-Test (JavaScript)
// npm install webdriverio @wdio/cli
const { remote } = require('webdriverio');
async function runTest() {
const driver = await remote({
protocol: 'http',
hostname: '127.0.0.1',
port: 4723,
path: '/',
capabilities: {
platformName: 'iOS',
'appium:automationName': 'XCUITest',
'appium:deviceName': 'iPhone 16',
'appium:platformVersion': '18.2',
'appium:app': '/path/to/MyApp.app'
}
});
try {
// Tap login button
const loginBtn = await driver.$('~loginButton');
await loginBtn.click();
// Enter credentials
const username = await driver.$('~usernameField');
await username.setValue('testuser@example.com');
const password = await driver.$('~passwordField');
await password.setValue('password123');
// Submit
const submit = await driver.$('~submitButton');
await submit.click();
// Verify
const welcome = await driver.$('~welcomeLabel');
const text = await welcome.getText();
console.assert(text.includes('Welcome'), 'Login test failed');
console.log('Test PASSED: Login successful');
} finally {
await driver.deleteSession();
}
}
runTest();
Selenium für Safari
macOS enthält Safari und safaridriver von Haus aus. Es sind keine zusätzlichen Browser-Treiber-Downloads erforderlich -- anders als bei Chrome oder Firefox auf anderen Plattformen.
safaridriver aktivieren
# Enable the Safari WebDriver (one-time setup) safaridriver --enable # Verify safaridriver is working safaridriver --version # For headless-like automation, enable "Allow Remote Automation" # in Safari > Settings > Advanced > Show Develop menu # Then: Develop > Allow Remote Automation # Or via command line: defaults write com.apple.Safari AllowRemoteAutomation 1
Selenium-Safari-Test (Python)
# pip install selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Create Safari driver
driver = webdriver.Safari()
try:
# Navigate to your web app
driver.get("https://your-webapp.com")
# Wait for page to load
wait = WebDriverWait(driver, 10)
# Find and click a button
login_link = wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "a.login-btn"))
)
login_link.click()
# Fill in form
email_input = wait.until(
EC.presence_of_element_located((By.ID, "email"))
)
email_input.send_keys("test@example.com")
password_input = driver.find_element(By.ID, "password")
password_input.send_keys("testpassword")
# Submit form
submit_btn = driver.find_element(By.CSS_SELECTOR, "button[type='submit']")
submit_btn.click()
# Verify redirect to dashboard
wait.until(EC.url_contains("/dashboard"))
assert "/dashboard" in driver.current_url
print("Test PASSED: Safari login flow works correctly")
finally:
driver.quit()
Selenium-Safari-Test (JavaScript)
// npm install selenium-webdriver
const { Builder, By, until } = require('selenium-webdriver');
async function safariTest() {
const driver = await new Builder()
.forBrowser('safari')
.build();
try {
await driver.get('https://your-webapp.com');
// Click login
const loginBtn = await driver.findElement(By.css('a.login-btn'));
await loginBtn.click();
// Fill form
const email = await driver.findElement(By.id('email'));
await email.sendKeys('test@example.com');
const password = await driver.findElement(By.id('password'));
await password.sendKeys('testpassword');
// Submit
const submit = await driver.findElement(
By.css("button[type='submit']")
);
await submit.click();
// Verify
await driver.wait(until.urlContains('/dashboard'), 10000);
const url = await driver.getCurrentUrl();
console.assert(url.includes('/dashboard'));
console.log('Test PASSED: Safari login flow works');
} finally {
await driver.quit();
}
}
safariTest();
Parallele Testausführung
Das parallele Ausführen von Tests verkürzt die Gesamtausführungszeit Ihrer Test-Suite drastisch. Der Mac Mini M4 Pro kann bequem 4-6 Simulator-Instanzen gleichzeitig ausführen.
Parallele XCTest-Tests
# Enable parallel testing with xcodebuild xcodebuild test \ -workspace MyApp.xcworkspace \ -scheme MyApp \ -destination 'platform=iOS Simulator,name=iPhone 16' \ -parallel-testing-enabled YES \ -parallel-testing-worker-count 4 \ -resultBundlePath ./TestResults/Parallel.xcresult # Parallel testing across multiple device types xcodebuild test \ -workspace MyApp.xcworkspace \ -scheme MyApp \ -destination 'platform=iOS Simulator,name=iPhone 16' \ -destination 'platform=iOS Simulator,name=iPhone SE (3rd generation)' \ -destination 'platform=iOS Simulator,name=iPad Pro 13-inch (M4)' \ -parallel-testing-enabled YES \ -resultBundlePath ./TestResults/MultiDeviceParallel.xcresult
Verwaltung von Simulator-Instanzen
# List all available simulators xcrun simctl list devices available # Create custom simulator instances for testing xcrun simctl create "Test-iPhone-1" "iPhone 16" "iOS 18.2" xcrun simctl create "Test-iPhone-2" "iPhone 16" "iOS 18.2" xcrun simctl create "Test-iPhone-3" "iPhone 16" "iOS 18.2" xcrun simctl create "Test-iPhone-4" "iPhone 16" "iOS 18.2" # Boot multiple simulators xcrun simctl boot "Test-iPhone-1" xcrun simctl boot "Test-iPhone-2" xcrun simctl boot "Test-iPhone-3" xcrun simctl boot "Test-iPhone-4" # Check booted simulators xcrun simctl list devices booted # Shut down all simulators xcrun simctl shutdown all # Delete all test simulators xcrun simctl delete "Test-iPhone-1" xcrun simctl delete "Test-iPhone-2" xcrun simctl delete "Test-iPhone-3" xcrun simctl delete "Test-iPhone-4"
Leistung bei parallelen Tests
| Konfiguration | Dauer von 200 UI-Tests | Geschwindigkeitsverbesserung |
|---|---|---|
| 1 Simulator (sequential) | 45 minutes | Baseline |
| 2 Simulators (parallel) | 24 minutes | 1.9x faster |
| 4 Simulators (parallel) | 13 minutes | 3.5x faster |
| 6 Simulators (parallel) | 10 minutes | 4.5x faster |
Hinweis: Ergebnisse gemessen auf einem Mac Mini M4 Pro (14 Kerne, 24 GB RAM). Die optimale Anzahl paralleler Simulatoren hängt von der Komplexität Ihrer Tests und den Speicheranforderungen ab. Für die meisten UI-Test-Suites bieten 4 parallele Worker das beste Gleichgewicht zwischen Geschwindigkeit und Stabilität.
CI/CD-Integration
Integrieren Sie Ihre automatisierten Tests in Ihre CI/CD-Pipeline für eine automatisierte Testausführung bei jedem Push, jeder Pull-Request oder in geplanten Intervallen.
GitHub-Actions-Workflow für automatisierte Tests
# .github/workflows/ios-tests.yml
name: iOS Automated Tests
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
schedule:
# Nightly regression tests at 2 AM UTC
- cron: '0 2 * * *'
jobs:
unit-tests:
name: Unit Tests
runs-on: self-hosted
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- name: Select Xcode version
run: sudo xcode-select -s /Applications/Xcode_16.2.app
- name: Resolve dependencies
run: |
xcodebuild -resolvePackageDependencies \
-workspace MyApp.xcworkspace \
-scheme MyApp
- name: Run unit tests
run: |
xcodebuild test \
-workspace MyApp.xcworkspace \
-scheme MyApp \
-destination 'platform=iOS Simulator,name=iPhone 16,OS=18.2' \
-parallel-testing-enabled YES \
-resultBundlePath $/UnitTests.xcresult
- name: Upload test results
if: always()
uses: actions/upload-artifact@v4
with:
name: unit-test-results
path: $/UnitTests.xcresult
ui-tests:
name: UI Tests
runs-on: self-hosted
timeout-minutes: 60
needs: unit-tests
steps:
- uses: actions/checkout@v4
- name: Select Xcode version
run: sudo xcode-select -s /Applications/Xcode_16.2.app
- name: Boot simulators for parallel testing
run: |
xcrun simctl boot "iPhone 16" || true
xcrun simctl boot "iPhone SE (3rd generation)" || true
- name: Run UI tests in parallel
run: |
xcodebuild test \
-workspace MyApp.xcworkspace \
-scheme MyAppUITests \
-destination 'platform=iOS Simulator,name=iPhone 16' \
-destination 'platform=iOS Simulator,name=iPhone SE (3rd generation)' \
-parallel-testing-enabled YES \
-parallel-testing-worker-count 4 \
-resultBundlePath $/UITests.xcresult
- name: Upload test results
if: always()
uses: actions/upload-artifact@v4
with:
name: ui-test-results
path: $/UITests.xcresult
- name: Cleanup simulators
if: always()
run: xcrun simctl shutdown all
Appium-Tests in CI ausführen
# Add to your GitHub Actions workflow
- name: Start Appium server
run: |
appium server --address 127.0.0.1 --port 4723 &
sleep 5
curl http://127.0.0.1:4723/status
- name: Build app for testing
run: |
xcodebuild build-for-testing \
-workspace MyApp.xcworkspace \
-scheme MyApp \
-destination 'platform=iOS Simulator,name=iPhone 16'
- name: Run Appium tests
run: |
cd tests/appium
pip install -r requirements.txt
pytest test_login.py test_checkout.py \
--junitxml=results.xml -v
- name: Stop Appium server
if: always()
run: pkill -f appium || true
Testberichte
Erstellen und verarbeiten Sie Testberichte, um Qualitätstrends zu verfolgen und fehlgeschlagene Tests schnell zu identifizieren.
Arbeiten mit xcresult-Bundles
# Get test results summary as JSON xcrun xcresulttool get \ --path ./TestResults.xcresult \ --format json # Get specific test action results xcrun xcresulttool get \ --path ./TestResults.xcresult \ --format json \ --id "REF_ID" # Export all attachments (screenshots, logs) xcrun xcresulttool export \ --path ./TestResults.xcresult \ --output-path ./artifacts \ --type attachments # Merge multiple xcresult bundles xcrun xcresulttool merge \ ./UnitTests.xcresult \ ./UITests.xcresult \ --output-path ./MergedResults.xcresult
In JUnit XML konvertieren
JUnit XML ist das universelle Format, das von CI/CD-Plattformen, Slack-Integrationen und Test-Dashboards unterstützt wird.
# Install xcresult-to-junit converter brew install chargepoint/xcparse/xcparse # Convert xcresult to JUnit XML xcparse tests ./TestResults.xcresult ./junit-results/ # Or use trainer (a popular Ruby gem) gem install trainer trainer --path ./TestResults.xcresult --output_directory ./reports # The generated JUnit XML works with: # - GitHub Actions test summaries # - Jenkins Test Result plugin # - GitLab CI test reporting # - Slack notifications via CI integrations
Screenshot bei Fehlschlag
// In your XCUITest, add screenshot capture on failure:
// XCTestCase+Screenshots.swift
import XCTest
extension XCTestCase {
override func tearDown() {
if testRun?.hasSucceeded == false {
let screenshot = XCUIScreen.main.screenshot()
let attachment = XCTAttachment(screenshot: screenshot)
attachment.name = "Failure-\(name)"
attachment.lifetime = .keepAlways
add(attachment)
}
super.tearDown()
}
}
Bewährte Methoden
Test-Isolation
Jeder Test sollte unabhängig sein und nicht auf dem Zustand vorheriger Tests beruhen. Setzen Sie den App-Zustand vor jedem Test zurück.
// In your XCUITest setUp() method:
override func setUp() {
super.setUp()
continueAfterFailure = false
let app = XCUIApplication()
app.launchArguments = ["--uitesting", "--reset-state"]
app.launchEnvironment = [
"DISABLE_ANIMATIONS": "1",
"UI_TEST_MODE": "true"
]
app.launch()
}
Simulator-Verwaltung
Bereinigen Sie Simulatoren zwischen Testläufen, um Zustandslecks und Speicherplatzprobleme zu vermeiden.
#!/bin/bash # cleanup-simulators.sh - Run before and after test suites # Shutdown all running simulators xcrun simctl shutdown all # Erase all simulator content and settings xcrun simctl erase all # Delete unavailable simulators xcrun simctl delete unavailable # Clear DerivedData rm -rf ~/Library/Developer/Xcode/DerivedData/* # Clear simulator logs rm -rf ~/Library/Logs/CoreSimulator/* echo "Simulator cleanup complete"
Animationen für mehr Geschwindigkeit deaktivieren
Deaktivieren Sie Animationen in Ihrer App während der UI-Tests, um die Testausführungszeit und Instabilität zu reduzieren.
// In your AppDelegate or App struct:
#if DEBUG
if CommandLine.arguments.contains("--uitesting") {
UIView.setAnimationsEnabled(false)
}
#endif
// Also disable Simulator animations via command line:
// Set Simulator > Debug > Slow Animations = OFF
defaults write com.apple.iphonesimulator SlowMotionAnimation -bool NO
Instabile Tests wiederholen
Nutzen Sie Xcodes integrierten Mechanismus zur Testwiederholung, um gelegentlich instabile UI-Tests zu handhaben.
# Retry failed tests up to 3 times xcodebuild test \ -workspace MyApp.xcworkspace \ -scheme MyAppUITests \ -destination 'platform=iOS Simulator,name=iPhone 16' \ -retry-tests-on-failure \ -test-iterations 3 \ -resultBundlePath ./TestResults.xcresult
Speicherplatz überwachen
Simulatoren und Test-Artefakte verbrauchen erheblichen Speicherplatz. Richten Sie eine automatisierte Bereinigung ein.
# Add to crontab for daily cleanup at midnight
# crontab -e
0 0 * * * /usr/local/bin/cleanup-test-artifacts.sh
# cleanup-test-artifacts.sh
#!/bin/bash
# Remove test results older than 7 days
find ~/TestResults -name "*.xcresult" -mtime +7 -delete
# Remove DerivedData older than 3 days
find ~/Library/Developer/Xcode/DerivedData \
-maxdepth 1 -mtime +3 -exec rm -rf {} +
# Remove old simulator logs
find ~/Library/Logs/CoreSimulator -mtime +3 -delete
# Check remaining disk space
df -h / | tail -1
Häufig gestellte Fragen
Wie viele parallele Simulatoren kann ein Mac Mini M4 Pro bewältigen?
Mit 14 CPU-Kernen und 24 GB RAM bewältigt der M4 Pro bequem 4-6 parallele iOS-Simulator-Instanzen für UI-Tests. Für reine Unit-Tests (ohne Simulator-GUI) können Sie sogar noch mehr parallele Worker ausführen. Wir empfehlen, mit 4 zu beginnen und je nach Speicheranforderungen Ihrer Test-Suite zu erhöhen.
Kann ich Tests headless ohne VNC ausführen?
Ja. XCTest- und Appium-Tests laufen vollständig über die Befehlszeile via SSH. Der iOS-Simulator läuft im "headless"-Modus, wenn er über xcodebuild ohne Anzeigesitzung gestartet wird. Sie benötigen während der Testausführung kein verbundenes VNC. VNC ist nur nützlich, um fehlgeschlagene Tests visuell zu debuggen.
Wie gehe ich mit instabilen UI-Tests um?
Stellen Sie zunächst die Test-Isolation sicher (App-Zustand vor jedem Test zurücksetzen). Deaktivieren Sie Animationen. Verwenden Sie explizite Wartezeiten statt sleep(). Nutzen Sie Xcodes Flag -retry-tests-on-failure, um fehlgeschlagene Tests automatisch zu wiederholen. Auf einem dedizierten Server wird Instabilität durch Ressourcenkonkurrenz eliminiert, was die häufigste Ursache für instabile Tests auf gemeinsam genutzten CI-Maschinen ist.
Kann ich auf echten iOS-Geräten von einem entfernten Mac aus testen?
Sie können keine physischen iOS-Geräte an einen entfernten Server anschließen (USB ist lokal). Der iOS-Simulator deckt jedoch die überwiegende Mehrheit der UI-Testszenarien ab. Für gerätespezifische Tests können Sie Apples "Xcode Cloud"-Gerätefarm nutzen oder Test-Builds über TestFlight für manuelle Gerätetests verteilen.
Wie sieht es mit Tests auf verschiedenen iOS-Versionen aus?
Sie können mehrere iOS-Simulator-Runtimes auf demselben Mac installieren. Verwenden Sie xcodebuild -downloadPlatform iOS für die neueste Version oder laden Sie ältere Runtimes über Xcode-Einstellungen > Plattformen herunter. Geben Sie dann die OS-Version in Ihrem Testziel an: -destination 'platform=iOS Simulator,name=iPhone 16,OS=17.5'.