Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 46 ยท Testing and Shipping

Testing View Models and UI

Learn to test iOS and SwiftUI apps: Swift Testing for logic, XCTest basics, UI tests with XCUIApplication, preview-driven development, async tests and fakes, with a test harness stand-in.

Code that "worked when I tried it" stops working the day you change something nearby. Tests are how you change an app with confidence. The most important testing trick for SwiftUI apps is not a framework at all: it is moving logic out of views. A body is hard to test, but a view model that turns inputs into plain state is easy. If you followed MVVM in SwiftUI and dependency injection through the environment, you have already built code that tests well.

This lesson covers the test pyramid for iOS, Swift Testing for fast logic tests, XCTest (still needed for UI tests and older projects), how to test async code with fakes, UI tests with XCUIApplication, and how Xcode previews act as a visual check. Test targets need Xcode, so real test code is read-only. The two TryIts are stand-ins: a small test harness that mimics @Test and #expect, and an async view-model test with a fake service.

The test pyramid for apps

Unit tests Many. Fast. Plain Swift logic.
Integration Some. Models with real storage.
UI tests Few. Slow. Whole app flows.

Put most checks at the bottom, where they are cheap.

1 / 2

What to test

Test behavior that can break and that you can describe in a sentence: "adding an item increases the total", "a failed request shows an error state", "an empty search clears the results". Skip tests that only restate the implementation, and do not try to test that Text draws text. The framework already does.

A good view model for testing has three properties:

  • Inputs are explicit. Dependencies arrive through the initializer (a protocol service, a Date or clock), not through singletons.
  • State is observable. Results sit in properties such as items, errorMessage or a LoadState enum, so a test can read them.
  • No UI types. It does not import SwiftUI, which also keeps the test target fast.

Swift Testing

Swift Testing (Xcode 16 and Swift 6) is the modern framework for unit tests. Tests are plain functions marked with @Test, and checks use the #expect macro with ordinary Swift expressions.

Swift
import Testing
@testable import ShopApp

struct CartTests {
    @Test func addingAnItemIncreasesTheTotal() {
        var cart = Cart()
        cart.add(Product(name: "Mug", price: 12.50))
        cart.add(Product(name: "Tea", price: 4.00))

        #expect(cart.items.count == 2)
        #expect(cart.total == 16.50)
    }

    @Test func emptyCartHasNoDiscount() {
        let cart = Cart()
        #expect(cart.discount == 0)
    }
}

Compared with older assertion functions, #expect shows you the values on both sides when it fails, so you rarely need a custom message. The pieces to know:

  • #require unwraps or stops the test early: let first = try #require(cart.items.first).
  • Errors: #expect(throws: CartError.empty) { try cart.checkout() }.
  • @Suite groups tests. A struct suite makes a fresh instance for every test, so put setup in init() and cleanup in deinit without any shared state leaking between tests.
  • Parameterized tests run one function for many inputs: @Test(arguments: [0, 1, 5]) func price(quantity: Int) { ... }. Each argument is reported as its own result.
  • Traits add metadata: .tags(.slow), .disabled("flaky"), .timeLimit(.minutes(1)).
  • Async tests are simply async functions. Mark them @MainActor when they touch main-actor view models.

Swift Testing covers logic and integration tests. It does not drive the user interface, and it runs side by side with XCTest in the same target.

The first TryIt is a miniature harness in plain Swift. It is not the real framework, but it models the same three ideas: tests are registered as named functions, expect records a failure instead of crashing, and a runner reports results. This lets you practice thinking in tests on this site, where Xcode is not available.

Swift A tiny test harness and a cart under test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The last test fails on purpose. Look at its message: a good failure says what was expected and what happened. The real #expect produces this automatically by capturing both sides of the comparison.

XCTest

XCTest is the original framework and is still required for UI tests, performance measurements and projects that have not moved yet. Tests are methods whose names begin with test inside an XCTestCase subclass:

Swift
import XCTest
@testable import ShopApp

final class CartXCTests: XCTestCase {
    private var cart: Cart!

    override func setUp() {
        super.setUp()
        cart = Cart()
    }

    func testAddingItemIncreasesTotal() {
        cart.add(Product(name: "Mug", price: 12.5))
        XCTAssertEqual(cart.total, 12.5, accuracy: 0.001)
    }

    func testCheckoutOfEmptyCartThrows() {
        XCTAssertThrowsError(try cart.checkout())
    }
}

Use XCTAssertEqual, XCTAssertTrue, XCTAssertNil and try XCTUnwrap(value). setUp() runs before every test method. Tests can be async and @MainActor. Older code uses XCTestExpectation and wait(for:timeout:) for callbacks, which you rarely need once code uses async/await. Both frameworks use the @testable import attribute to reach internal types of your app target.

Testing async code

Async view models are tested by awaiting them and inspecting the state afterward. The key is a fake that implements the same protocol as the real service, so no network is involved and the result is exactly what you choose.

Swift
protocol WeatherService: Sendable {
    func forecast(for city: String) async throws -> Forecast
}

struct FakeWeatherService: WeatherService {
    var result: Result<Forecast, Error>
    func forecast(for city: String) async throws -> Forecast { try result.get() }
}

@MainActor
struct WeatherViewModelTests {
    @Test func successShowsForecast() async {
        let model = WeatherViewModel(service: FakeWeatherService(result: .success(.sample)))
        await model.load(city: "Oslo")
        #expect(model.state == .loaded(.sample))
    }
}

Avoid Task.sleep to "wait long enough": it is slow and flaky. Instead await the work directly, or inject a clock or a controllable fake that you resume yourself. When a callback style API cannot be awaited, Swift Testing offers confirmation("done") { confirm in ... } to assert an event happens.

The second TryIt runs this idea. A LoadState enum describes the screen (idle, loading, loaded, failed), the view model records every state it passes through, and fakes decide the outcome. It is the same shape as the real thing, as in networking with URLSession.

Swift Testing an async view model with fakes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both outcomes are tested without a network or a delay. The fake is what makes the failure path reachable: you cannot reliably make a real server fail on demand.

UI tests

UI tests launch your actual app in a separate process and drive it like a user, through XCTest's XCUIApplication. They are slower and more fragile than unit tests, so keep them for the few flows that matter most, such as sign-in, checkout or onboarding.

Swift
import XCTest

final class AddItemUITests: XCTestCase {
    override func setUpWithError() throws {
        continueAfterFailure = false
    }

    func testAddingATaskShowsItInTheList() throws {
        let app = XCUIApplication()
        app.launchArguments = ["-uiTesting"]
        app.launch()

        app.buttons["addTaskButton"].tap()

        let field = app.textFields["taskTitleField"]
        XCTAssertTrue(field.waitForExistence(timeout: 2))
        field.tap()
        field.typeText("Buy milk")
        app.buttons["saveTaskButton"].tap()

        XCTAssertTrue(app.staticTexts["Buy milk"].exists)
    }
}

Practical advice:

  • Find elements by accessibility identifier, set with .accessibilityIdentifier("addTaskButton"). Identifiers are not spoken and do not change with localization, unlike labels.
  • Wait, do not sleep. Use waitForExistence(timeout:).
  • Control the environment. Launch arguments and launchEnvironment can switch the app to an in-memory store, fake network and a fixed date. Read them at startup with ProcessInfo.processInfo.
  • Keep each test independent so it can run alone; reset state in launch.
  • Recent SDKs include performAccessibilityAudit() in UI tests, which flags missing labels and tiny touch targets. It connects well with the accessibility lesson.

Test plans in Xcode let you group unit tests and UI tests, run them in several languages or configurations, and collect code coverage. Press Cmd+U to run the plan. Treat coverage as a map of untested areas, not a score to maximize.

Preview-driven development

Xcode previews are not tests, but they work as a fast visual check. A #Preview macro renders a view with sample data without launching the app:

Swift
#Preview("Loaded") {
    QuotesView(model: QuotesViewModel(service: FakeService(result: .success(["Ship it"]))))
}

#Preview("Failed") {
    QuotesView(model: QuotesViewModel(service: FakeService(result: .failure(.offline))))
}

Use previews to look at every state you test in logic: loading, empty, error, very long text, large Dynamic Type, dark mode, right-to-left. The same fakes you wrote for tests feed the previews, which is a strong reason to keep dependencies behind protocols. Pixel-perfect snapshot tests exist in third-party libraries, but that is an extra dependency and beyond this lesson.

Habits that keep tests useful

  • Name tests as sentences describing behavior.
  • One idea per test; arrange, act, assert.
  • Tests must not depend on order, the clock, the network or the real file system.
  • When a bug is reported, write a failing test first, then fix it.
  • Keep UI tests few and stable; keep logic tests many and fast.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is it easier to test a view model than a SwiftUI view's body?

    Logic in a view model is just Swift: call a method, read the resulting state. A body returns a description that is not meant to be inspected.
  2. 2. What does a struct suite in Swift Testing guarantee?

    Each test gets a new instance, so state from one test cannot leak into another. Use init for setup.
  3. 3. Which framework is required for UI tests that tap buttons in a running app?

    UI automation is provided by XCTest. Swift Testing is for logic-level tests.
  4. 4. How should you test code that depends on a network call?

    A fake gives deterministic success and failure without delays, so the test is fast and reliable.
  5. 5. What is the best way to find a button in a UI test?

    Identifiers are stable and independent of language and layout.

Summary

  • Move logic into view models with explicit dependencies, observable state and no UI imports; then it is easy to test.
  • Swift Testing uses @Test, #expect, #require, @Suite and parameterized arguments; XCTest uses XCTestCase and XCTAssert... and remains necessary for UI tests.
  • Test async code by awaiting it and injecting fakes; avoid sleeping.
  • UI tests drive the real app through XCUIApplication; use accessibility identifiers, waitForExistence and launch arguments, and keep them few.
  • Previews with the same fakes let you check loading, empty, error and accessibility states visually.

Next: Debugging Xcode Apps.