1 minute read

Unit Testing Swift Code in Xcode: A Practical Guide

Most Swift projects start as a single file with a handful of functions and a view controller that looks perfectly reasonable on screen. The trouble arrives later, when a new requirement from a product team in Sydney, a design tweak from a client in Melbourne, or a bug report from a user in Brisbane changes one small rule buried in that code. A unit test is the cheapest way to find out whether the change broke anything else.

There is also a career argument for writing them. Australian software teams, from Canva and Atlassian to the fintech and ecommerce companies clustered around Melbourne and Sydney, tend to ask junior developers how they verify their work, and "I ran it on my phone" is a weaker answer than a suite that goes green and red on demand. Xcode gives you that suite for free, so the real skill is not tooling. It is knowing how to express a rule as a test.

The example running through this guide is a small coffee-order calculator: the kind of app that prices a flat white, a long black, or an extra shot, applies a promo code, and returns a total in dollars. It is deliberately simple, because the app is not the point. The pattern is the point: keep the rules in plain Swift types, exercise them from a test bundle, and let the suite tell you when behaviour and expectations drift apart.

Why unit tests matter more than they look

A unit test is an executable sentence. Something like "promo code BREKKIE10 takes ten percent off orders over ten dollars" is a sentence you can read, and it can also run in milliseconds and fail loudly when someone renames the discount field at 6pm on a Friday.

That second benefit surprises people. Writing tests pushes you to pull logic out of view controllers and into value types and functions, which makes your UIKit layer thinner and your code easier to reason about. A view controller that only wires up outlets and calls a pricing function is easier to review, easier to reuse, and far easier to test than one that calculates a total inline. The test suite and the architecture improve each other.

It helps to separate unit tests from UI tests. A UI test taps buttons on a simulator, waits for animations, and takes seconds. A unit test calls a Swift method directly and takes microseconds, which means you can run hundreds of them while you wait for a coffee in a Melbourne laneway café. Push the logic down into testable types and keep the slow UI tests for the handful of flows that genuinely need a simulator.

Adding a test target to your Xcode project

Open your project in Xcode and choose File, then New, then Target. Pick the Unit Testing Bundle template, give it a name such as AppNameTests, and set the target to test as your main application. Choose Swift as the language and let Xcode generate the files. The new bundle appears in the Project navigator as a separate target, and from now on your test code lives entirely outside the app target, which is exactly what you want.

Next, check the scheme. Product, Scheme, then Edit Scheme, and make sure the Test action includes your new bundle. Without that step the test navigator stays empty and you will spend ten minutes convinced the template broke something. Share the scheme so CI can find it later. In recent Xcode versions you can also add a test plan file, which lets you define separate suites, run them in parallel, and configure code coverage collection for a single scheme.

The Test navigator in the left sidebar lists every test method. Clicking the diamond beside a class or method runs it, and Command-U runs everything attached to the scheme. If your tests cannot see internal types, add @testable import AppName at the top of the test file. That import only works when the bundle has a test host, so make sure your scheme targets the app rather than hosting tests in a library-less environment.

Writing your first test case

Everything starts with a subclass of XCTestCase. The example app models an order as a plain struct so that pricing can be verified without any simulator at all.

struct CoffeeOrder {
    enum Size: Double {
        case small = 3.50
        case regular = 4.50
        case large = 5.50
    }

    let size: Size
    let shots: Int
    let promo: String?

    var basePrice: Double {
        size.rawValue + Double(shots - 1) * 0.80
    }

    var total: Double {
        guard let promo, promo == "BREKKIE10", basePrice > 10 else {
            return basePrice
        }
        return basePrice * 0.9
    }
}

The test then states the rule and checks it. Name methods so the failure message reads like a sentence, since Xcode prints the method name next to the red result.

import XCTest
@testable import CoffeeApp

final class CoffeeOrderTests: XCTestCase {

    func testRegularFlatWhiteCostsFourFifty() {
        let order = CoffeeOrder(size: .regular, shots: 1, promo: nil)
        XCTAssertEqual(order.basePrice, 4.50, accuracy: 0.001)
    }

    func testPromoCodeAppliesTenPercentDiscount() {
        let order = CoffeeOrder(size: .large, shots: 1, promo: "BREKKIE10")
        XCTAssertEqual(order.total, 5.50 * 0.9, accuracy: 0.001)
    }
}

setUp and tearDown run before and after every method, which is where you create temporary state or reset a shared helper. Assertions come in a small family: XCTAssertEqual, XCTAssertTrue, XCTAssertFalse, XCTAssertNil, XCTAssertNotNil, and XCTAssertGreaterThan. Any of them accepts a custom message, and a good message turns a vague failure into a useful one, such as "the wrong discount should have been applied to a large coffee with an extra shot".

Covering optionals, errors, and edge cases

Optionals deserve their own attention because they represent missing data rather than empty data. Use XCTAssertNil when a promo code is absent and XCTAssertNotNil when a required field is missing, and remember that asserting on an optional with XCTAssertEqual will not compile, since the types do not match.

Errors are the other half of the picture. A discount service that rejects an unknown promo code should throw, and XCTAssertThrowsError confirms the behaviour in a single line. Understanding how a thrown error travels back through your call stack makes that assertion easier to read, and this guide to handling errors with do-catch covers the mechanics of throwing and catching in Swift.

Edge cases are where real users and real money meet. An empty basket, a single item, an order of ten coffees, a promo code with a trailing space, and a total that lands exactly on a round dollar amount all deserve a test. If your app pulls prices from a supermarket catalogue, the arithmetic has to reconcile with a receipt, so test rounding to the nearest cent rather than trusting binary floating point. A table of tuples keeps a family of related cases tidy.

func testPromoCodeIsCaseSensitive() {
    let order = CoffeeOrder(size: .regular, shots: 1, promo: "brekkie10")
    XCTAssertEqual(order.total, 4.50, accuracy: 0.001)
}

Injecting dependencies and using test doubles

The fastest unit test in the world still fails if it calls the network, so introduce a seam. Declare a protocol for anything that leaves your process, then inject a small double into the type under test.

protocol WeatherServing {
    func forecast(for city: String) throws -> Weather
}

struct StubWeatherService: WeatherServing {
    func forecast(for city: String) throws -> Weather {
        Weather(temperatureCelsius: 18, summary: "Partly cloudy")
    }
}

Stubs return canned values, mocks record what they were asked, and spies observe calls. Use them sparingly, because a test double that reimplements your logic just gives you two places to maintain. Prefer real value types for calculations and reserve doubles for boundaries such as the network, the file system, or the clock.

Injecting time is worth the effort. Code that calls Date() directly behaves differently on a Tuesday and on the morning daylight saving begins, when clocks in Sydney and Melbourne move forward in October and back again in April. Pass a date into the function under test and those tests become deterministic.

Keep synthetic data in your fixtures too. Australian consumer and privacy rules, including the Privacy Act 1988 and the Australian Privacy Principles that sit under it, expect real customer information to be handled carefully, so test suites should generate fake names, fake addresses, and fake order numbers rather than copying production records into a repository.

Measuring coverage and what to keep in mind

Xcode can report how much of your code the suite touched. Run Product, then Code Coverage, or open the coverage tab beside the editor. Red lines were never executed, and a high percentage proves very little on its own: a function can be called with one input and still contain an untested branch. Read coverage as a map of what your tests actually exercise, not as a score to optimise.

The same habits travel well into continuous integration. A GitHub Actions workflow on a macOS runner can call xcodebuild test for every pull request, and a scheduled nightly run in Australian Eastern Standard Time catches failures that only appear at particular hours of the day. Quarantine a flaky test, fix it, and move on, because a suite people distrust is a suite people ignore.

What should stay with you is smaller than any of this tooling. Each test is one rule written down in a language the computer can check, and a good suite is built rule by rule rather than installed in one afternoon. Start with the plain value type, the one function that holds your pricing logic, and write down what it promises. Everything after that, the doubles, the coverage reports, the CI pipeline, is support for that single habit.

Updated: