iOS XCTest & XCUITest Deep Dive

iOS XCTest & XCUITest Deep Dive

Apple's testing frameworks ship inside Xcode and require no third-party dependencies. XCTest handles unit and integration tests; XCUITest handles UI automation. Together they cover the full iOS testing spectrum, and their deep integration with Xcode gives you capabilities — parallel simulator execution, code coverage, test plans — that are difficult to replicate with external frameworks.

This guide covers both frameworks in depth, from writing your first unit test through configuring parallel execution in CI.

XCTest vs XCUITest: What Each Covers

Aspect XCTest XCUITest
What it tests Units of code in process UI interactions out of process
Speed Very fast (ms per test) Slow (seconds per test)
App access Direct (same process) Via accessibility tree only
Mocking Full control No direct mocking
Flakiness Low Higher
Parallel execution Per-class Per-simulator clone
Use case Logic, models, ViewModels User flows, screen transitions

Setting Up XCTest

XCTest comes configured by default in Xcode projects. Your test target links the XCTest framework and the test bundle is embedded in the app for testing.

Create a new unit test file from File > New > File > Unit Test Case Class. The generated stub:

import XCTest
@testable import MyApp

final class CartViewModelTests: XCTestCase {

    var sut: CartViewModel!  // sut = system under test

    override func setUp() {
        super.setUp()
        sut = CartViewModel()
    }

    override func tearDown() {
        sut = nil
        super.tearDown()
    }

    func test_addItem_incrementsCount() {
        let item = Product(id: "p1", name: "Widget", price: 9.99)
        sut.add(item)
        XCTAssertEqual(sut.itemCount, 1)
    }
}

The @testable import gives your tests access to internal declarations without making them public.

XCTest Assertions

// Equality
XCTAssertEqual(result, expected)
XCTAssertNotEqual(a, b)

// Boolean
XCTAssertTrue(condition)
XCTAssertFalse(condition)

// Nil checks
XCTAssertNil(value)
XCTAssertNotNil(value)

// Comparison
XCTAssertGreaterThan(a, b)
XCTAssertLessThanOrEqual(a, b)

// Throwing
XCTAssertThrowsError(try dangerousFunction()) { error in
    XCTAssertEqual(error as? AppError, AppError.invalidInput)
}
XCTAssertNoThrow(try safeFunction())

// Custom message
XCTAssertEqual(actual, expected, "Cart count should be 2 after adding two items")

Async Testing

Modern iOS code is async. XCTest supports async tests natively:

func test_fetchUser_returnsCorrectData() async throws {
    let service = UserService(client: MockHTTPClient())
    let user = try await service.fetchUser(id: "user-123")

    XCTAssertEqual(user.name, "Alice")
    XCTAssertEqual(user.email, "alice@example.com")
}

func test_fetchUser_throwsOnNetworkError() async {
    let client = MockHTTPClient()
    client.stubbedError = URLError(.notConnectedToInternet)
    let service = UserService(client: client)

    do {
        _ = try await service.fetchUser(id: "user-123")
        XCTFail("Expected error to be thrown")
    } catch {
        XCTAssertEqual((error as? URLError)?.code, .notConnectedToInternet)
    }
}

For Combine publishers, use XCTestExpectation:

func test_publisherEmitsUserOnSuccess() throws {
    let expectation = expectation(description: "User published")
    let service = UserService(client: MockHTTPClient())
    var receivedUser: User?

    let cancellable = service.userPublisher(id: "user-123")
        .sink(
            receiveCompletion: { _ in },
            receiveValue: { user in
                receivedUser = user
                expectation.fulfill()
            }
        )

    wait(for: [expectation], timeout: 2.0)

    XCTAssertEqual(receivedUser?.name, "Alice")
    _ = cancellable
}

Testing ViewModels (MVVM)

ViewModels are the sweet spot for XCTest — they contain business logic, are independent of UIKit, and can be tested without any UI setup:

@MainActor
final class LoginViewModelTests: XCTestCase {

    var sut: LoginViewModel!
    var mockAuthService: MockAuthService!

    override func setUp() {
        super.setUp()
        mockAuthService = MockAuthService()
        sut = LoginViewModel(authService: mockAuthService)
    }

    func test_login_setsLoadingState() async {
        mockAuthService.loginDelay = 0.5

        let task = Task { await sut.login(email: "a@b.com", password: "pass") }

        // Check loading state is set before response arrives
        try? await Task.sleep(nanoseconds: 100_000_000)
        XCTAssertEqual(sut.state, .loading)

        await task.value
    }

    func test_login_setsSuccessOnValidCredentials() async {
        mockAuthService.stubbedToken = "auth-token-123"

        await sut.login(email: "user@example.com", password: "password123")

        XCTAssertEqual(sut.state, .success)
        XCTAssertEqual(sut.authToken, "auth-token-123")
    }

    func test_login_setsErrorOnFailure() async {
        mockAuthService.stubbedError = AuthError.invalidCredentials

        await sut.login(email: "wrong@example.com", password: "bad")

        guard case .error(let message) = sut.state else {
            XCTFail("Expected error state")
            return
        }
        XCTAssertEqual(message, "Invalid email or password")
    }

    func test_login_validatesEmptyEmail() async {
        await sut.login(email: "", password: "password")

        guard case .error(let message) = sut.state else {
            XCTFail("Expected validation error")
            return
        }
        XCTAssertEqual(message, "Email is required")
        XCTAssertFalse(mockAuthService.loginWasCalled)
    }
}

Integration Tests with XCTest

Integration tests in XCTest sit between unit tests and UI tests — they test multiple real components working together without the overhead of UI automation:

final class CheckoutIntegrationTests: XCTestCase {

    func test_fullCheckoutFlow() async throws {
        // Real implementations, not mocks
        let cartRepository = InMemoryCartRepository()
        let paymentService = PaymentService(apiClient: SandboxPaymentClient())
        let orderRepository = InMemoryOrderRepository()

        let checkoutCoordinator = CheckoutCoordinator(
            cart: cartRepository,
            payment: paymentService,
            orders: orderRepository
        )

        // Add items to cart
        try await cartRepository.add(Product(id: "p1", price: 29.99))
        try await cartRepository.add(Product(id: "p2", price: 14.99))

        // Complete checkout
        let order = try await checkoutCoordinator.checkout(
            card: CreditCard(number: "4242424242424242", expiry: "12/26", cvv: "123")
        )

        XCTAssertEqual(order.status, .confirmed)
        XCTAssertEqual(order.total, 44.98, accuracy: 0.01)
        XCTAssertTrue(try await cartRepository.isEmpty())
    }
}

XCUITest: UI Automation

XCUITest runs in a separate process from your app and communicates through the accessibility layer. This isolation makes it more realistic (it tests what the user actually sees) but also means you can't inject mocks directly.

Create a UI test target in Xcode and add your first test:

import XCTest

final class LoginUITests: XCTestCase {

    var app: XCUIApplication!

    override func setUp() {
        super.setUp()
        continueAfterFailure = false
        app = XCUIApplication()
        app.launchArguments = ["--uitesting"]
        app.launch()
    }

    func test_loginWithValidCredentials() {
        let emailField = app.textFields["email-input"]
        let passwordField = app.secureTextFields["password-input"]
        let loginButton = app.buttons["Log In"]

        XCTAssertTrue(emailField.waitForExistence(timeout: 3))

        emailField.tap()
        emailField.typeText("user@example.com")

        passwordField.tap()
        passwordField.typeText("password123")

        loginButton.tap()

        let homeScreen = app.otherElements["home-screen"]
        XCTAssertTrue(homeScreen.waitForExistence(timeout: 5))
    }

    func test_showsErrorForInvalidCredentials() {
        app.textFields["email-input"].tap()
        app.textFields["email-input"].typeText("bad@email.com")
        app.secureTextFields["password-input"].tap()
        app.secureTextFields["password-input"].typeText("wrongpassword")
        app.buttons["Log In"].tap()

        let error = app.staticTexts["Invalid credentials"]
        XCTAssertTrue(error.waitForExistence(timeout: 3))
    }
}

Set accessibility identifiers in your SwiftUI or UIKit code:

// SwiftUI
TextField("Email", text: $email)
    .accessibilityIdentifier("email-input")

// UIKit
emailTextField.accessibilityIdentifier = "email-input"

XCUITest Element Queries

let app = XCUIApplication()

// By accessibility identifier (preferred)
app.buttons["submit-button"]
app.textFields["email-input"]
app.cells["product-cell"]

// By label/text
app.buttons.matching(identifier: "Cancel").firstMatch
app.staticTexts["Welcome back"]

// By type
app.buttons.element(boundBy: 0)  // First button
app.textFields.count              // Count all text fields

// Navigation bars
app.navigationBars["My Title"].buttons["Back"]

// Tables and collections
app.tables.cells.element(boundBy: 2)  // Third cell
app.collectionViews.cells.containing(.staticText, identifier: "Product Name").element

// Predicates for complex queries
let predicate = NSPredicate(format: "label BEGINSWITH 'Delete'")
app.buttons.matching(predicate).firstMatch

Test Plans

Test plans (.xctestplan files) let you organize tests into named configurations with different settings — code coverage, environment variables, language/region, sanitizers:

Create via Product > Test Plan > New Test Plan. A plan file looks like:

{
  "configurations": [
    {
      "id": "unit-tests",
      "name": "Unit Tests",
      "options": {
        "codeCoverageTargets": ["MyApp"],
        "environmentVariableEntries": [
          { "key": "API_BASE_URL", "value": "http://localhost:3001" }
        ],
        "uiTestingScreenshotsLifetime": "deleteOnSuccess"
      }
    },
    {
      "id": "ui-tests-en",
      "name": "UI Tests — English",
      "options": {
        "language": "en",
        "region": "US",
        "uiTestingScreenshotsLifetime": "keepAlways"
      }
    },
    {
      "id": "ui-tests-fr",
      "name": "UI Tests — French",
      "options": {
        "language": "fr",
        "region": "FR"
      }
    }
  ],
  "testTargets": [
    {
      "target": { "name": "MyAppTests" },
      "skippedTests": []
    }
  ]
}

Run a specific plan from the command line:

xcodebuild test \
  -scheme MyApp \
  -testPlan "unit-tests" \
  -destination "platform=iOS Simulator,name=iPhone 15"

Parallel Execution on Simulators

Xcode can run tests across multiple simulator clones simultaneously. Enable in your scheme's Test action:

xcodebuild test \
  -scheme MyApp \
  -destination "platform=iOS Simulator,name=iPhone 15" \
  -parallel-testing-enabled YES \
  -parallel-testing-worker-count 4

Xcode creates 4 simulator clones and distributes test classes across them. A suite that takes 8 minutes on a single simulator finishes in around 2 minutes with 4-way parallelism.

Important constraint: Parallel tests must not share mutable state — no shared files, no shared SQLite databases, no shared UserDefaults. Each worker gets an isolated app sandbox, so well-written tests parallelize without issues.

Code Coverage

Enable code coverage in your scheme or test plan, then retrieve the report:

xcodebuild test \
  -scheme MyApp \
  -destination "platform=iOS Simulator,name=iPhone 15" \
  -enableCodeCoverage YES \
  -resultBundlePath TestResults.xcresult

Convert to readable formats:

# Generate coverage report from result bundle
xcrun xccov view --report TestResults.xcresult

# Export as JSON for tooling
xcrun xccov view --report --json TestResults.xcresult > coverage.json

For CI, tools like slather or xcov can generate HTML coverage reports or post coverage summaries to pull requests.

CI with GitHub Actions

name: iOS Tests

on:
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: macos-14

    steps:
      - uses: actions/checkout@v4

      - name: Select Xcode
        run: sudo xcode-select -s /Applications/Xcode_15.4.app

      - name: Cache SPM packages
        uses: actions/cache@v4
        with:
          path: .build
          key: spm-${{ hashFiles('Package.resolved') }}

      - name: Run unit tests
        run: |
          xcodebuild test \
            -scheme MyApp \
            -testPlan "unit-tests" \
            -destination "platform=iOS Simulator,name=iPhone 15,OS=17.5" \
            -parallel-testing-enabled YES \
            -resultBundlePath unit-results.xcresult \
            | xcbeautify

      - name: Run UI tests
        run: |
          xcodebuild test \
            -scheme MyApp \
            -testPlan "ui-tests-en" \
            -destination "platform=iOS Simulator,name=iPhone 15,OS=17.5" \
            -resultBundlePath ui-results.xcresult \
            | xcbeautify

      - name: Upload results
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: test-results
          path: "*.xcresult"

xcbeautify formats the raw xcodebuild output into readable test results. Install it with brew install xcbeautify.

Performance Testing

XCTest includes a performance measurement API:

func test_sortPerformance() {
    let items = (0..<10_000).map { Product(id: "\($0)", price: Double($0)) }

    measure {
        _ = items.sorted { $0.price < $1.price }
    }
}

The measure block runs 10 times and reports average duration. Set a baseline — the test will fail if performance regresses beyond a threshold. Baselines are stored in .xcbaseline files committed to your repository.

XCTest and XCUITest are the most direct path to reliable iOS test coverage. They require no configuration beyond a standard Xcode project, they improve with every Xcode release, and their output integrates natively with every Apple CI tool — including Xcode Cloud and the TestFlight distribution pipeline.

Read more

Start now free