Best Practices

Write reliable, maintainable XCUITest suites.

Best practices checklist

text
✅ Set accessibilityIdentifier on all testable elements in your app code
✅ Use waitForExistence(timeout:) instead of sleep()
✅ Set continueAfterFailure = false in setUp
✅ Use launchArguments to skip onboarding/auth in tests
✅ Reset app state with launchEnvironment rather than deleting and reinstalling
✅ Use XCTContext.runActivity() to label test steps in the report
✅ Prefer app.buttons["identifier"] over long XPath-style chains
✅ Keep tests short and focused — one behavior per test
✅ Use Page Object pattern: create helper structs per screen
✅ Run on simulator for speed; real device for final validation
✅ Enable parallel testing: Product → Test → Options → Execute in parallel

Screen helper (Page Object for XCUITest)

swift
struct LoginScreen {
    let app: XCUIApplication

    var emailField: XCUIElement { app.textFields["email-field"] }
    var passwordField: XCUIElement { app.secureTextFields["password-field"] }
    var loginButton: XCUIElement { app.buttons["login-button"] }
    var errorLabel: XCUIElement { app.staticTexts["error-label"] }

    func login(email: String, password: String) {
        emailField.tap()
        emailField.typeText(email)
        passwordField.tap()
        passwordField.typeText(password)
        loginButton.tap()
    }
}

// In test:
let screen = LoginScreen(app: app)
screen.login(email: "alice@example.com", password: "pass123")
XCTAssertTrue(app.staticTexts["Dashboard"].waitForExistence(timeout: 5))