Writing reliable Swift code starts with tests you can trust. This guide covers everything from the foundations of XCTest to modern Swift Testing patterns.


Table of Contents

  1. What is XCTest and Why It Matters
  2. Best Practices
  3. What's New with Swift Testing

What is XCTest and Why It Matters

XCTest is Apple's native testing framework, bundled directly into Xcode and available across all Apple platforms — iOS, macOS, watchOS, tvOS, and visionOS. It has been the standard tool for unit testing Swift (and Objective-C) code since Xcode 5, and it remains the backbone of automated quality assurance in the Apple ecosystem.

The Core Purpose

At its heart, XCTest exists to let you verify that your code does exactly what you intend it to do — not just today, but after every future change. It serves several concrete goals:

Anatomy of an XCTest Test Case

A test lives inside a class that inherits from XCTestCase. Each test method must start with the word test, take no arguments, and return void.

import XCTest
@testable import MyApp

final class CurrencyFormatterTests: XCTestCase {

    var formatter: CurrencyFormatter!

    // MARK: - Lifecycle

    override func setUp() {
        super.setUp()
        formatter = CurrencyFormatter(locale: Locale(identifier: "en_US"))
    }

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

    // MARK: - Tests

    func testFormatsPositiveAmountCorrectly() {
        let result = formatter.string(from: 1_234.56)
        XCTAssertEqual(result, "$1,234.56")
    }

    func testFormatsZeroAsZeroDollars() {
        let result = formatter.string(from: 0)
        XCTAssertEqual(result, "$0.00")
    }

    func testFormatsNegativeAmountWithMinusSign() {
        let result = formatter.string(from: -99.99)
        XCTAssertEqual(result, "-$99.99")
    }
}

The XCTest Assertion Toolkit

XCTest provides a rich set of assertion functions: