Testing and architecture

5 concepts · 10 practice questions

XCTest and Swift Testing

XCTest uses XCTestCase subclasses, methods whose names start with test, and XCTAssert functions. Swift Testing, the newer framework, uses @Test functions, #expect for checks that record a failure and carry on, and #require for checks that stop the test. Arguments turn one test into many parameterized cases. Swift Testing runs tests in parallel by default and creates a fresh suite instance for each test, so avoid shared global state or mark the suite .serialized. Both frameworks support async tests.

import Testing

@Suite struct PriceFormatterTests {
    let formatter = PriceFormatter(locale: Locale(identifier: "en_US"))

    @Test(arguments: [(0, "$0.00"), (1999, "$19.99"), (100_000, "$1,000.00")])
    func formatsCents(cents: Int, expected: String) {
        #expect(formatter.string(cents: cents) == expected)
    }

    @Test func parsesNegativeAmounts() throws {
        let cents = try #require(formatter.parse("-$5.00"))   // stops the test if nil
        #expect(cents == -500)
    }
}

Also covered

Test doubles
Dependency injection
MVVM and coordinators
Modularizing with Swift packages

Sign in to read the rest and take the 10-question test.

Sign in to continue