Skip to content

Migrating from XCTest to Swift Testing: what maps across, and what changes underneath

Move an iOS test suite from XCTest to Swift Testing: assertion mapping, setup and teardown, async tests, parallel runs and what must stay in XCTest.

· 7 min read

  • Swift Testing
  • XCTest
  • Swift

Swift Testing is Apple’s newer test framework, and it ships with the Swift 6 toolchain in Xcode 16 and later. Converting a test is mostly mechanical: XCTAssertEqual(a, b) becomes #expect(a == b). A migration that only does that will compile and pass, and can still leave you with tests that behave differently from before.

The differences that matter are not in the assertion macros. They are in how tests are isolated, how they are scheduled, and what happens after a failure. This article covers the mapping, then those differences, then what you should leave in XCTest.

We could not compile Swift in the environment where we wrote this, so we checked the APIs and behaviour against the Swift Testing documentation and its source, and based the snippets on its examples. Build them in Xcode before relying on them.

Migrate in small steps

You don’t need a big-bang rewrite. A test target can contain both XCTest and Swift Testing tests, and a single file can import both XCTest and Testing. Newer toolchains add an interoperability feature, so that an XCTest assertion in a shared helper still fails a Swift Testing test. According to the current migration guide, the default mode is none below Swift 6.4, and you can set it with the SWIFT_TESTING_XCTEST_INTEROP_MODE environment variable. Don’t rely on it unless you have set it deliberately. The simpler route is to move shared helpers to #expect first, which works from both frameworks.

Start with pure logic tests (models, parsers, view models), then async and callback tests.

The mapping

Remove XCTestCase, drop the test prefix and add @Test. Each XCTAssert variant becomes #expect or #require. This is the table from the migration guide, trimmed to the cases you will meet most:

XCTest Swift Testing
XCTAssertTrue(x) #expect(x)
XCTAssertEqual(x, y) #expect(x == y)
XCTAssertNil(x) #expect(x == nil)
XCTAssertGreaterThan(x, y) #expect(x > y)
try XCTUnwrap(x) try #require(x)
XCTFail("…") Issue.record("…")
XCTAssertThrowsError(try f()) #expect(throws: (any Error).self) { try f() }
XCTAssertNoThrow(try f()) #expect(throws: Never.self) { try f() }

Before and after for a small type:

// Before
final class BasketTests: XCTestCase {
    func testTotalAppliesDiscount() throws {
        let basket = Basket(items: [.init(price: 1000), .init(price: 500)])
        let discounted = try XCTUnwrap(basket.applying(code: "SAVE10"))
        XCTAssertEqual(discounted.total, 1350)
    }
}
// After
import Testing

struct BasketTests {
    @Test func totalAppliesDiscount() throws {
        let basket = Basket(items: [.init(price: 1000), .init(price: 500)])
        let discounted = try #require(basket.applying(code: "SAVE10"))
        #expect(discounted.total == 1350)
    }
}

Two things are better straight away. #expect captures the whole expression, so a failure reports the values on both sides of == instead of “not equal”. And #expect(throws:) returns the thrown error, so you can inspect it:

@Test func rejectsUnknownCode() {
    let error = #expect(throws: Basket.DiscountError.self) {
        try Basket(items: []).applyingOrThrow(code: "NOPE")
    }
    #expect(error == .unknownCode("NOPE"))
}

There is no direct replacement for XCTAssertEqual(_:_:accuracy:). The migration guide points to isApproximatelyEqual() from the swift-numerics package, or you can write a small helper.

What changes underneath

A failed #expect does not stop the test

In XCTest, a failed assertion records a failure and the test carries on, unless you set continueAfterFailure = false. #expect works the same way. If the next line depends on the previous check, use #require, which throws and ends the test. When you convert, look at each XCTAssert followed by code that would crash or give noise if it failed, and make it a #require.

try #require(...) also replaces continueAfterFailure = false. That XCTest setting works by throwing an Objective-C exception, which the migration guide notes can terminate the process in async code.

Every test gets a fresh instance

A suite is a plain type, usually a struct. For instance methods, the framework creates a new instance for each test function. So init() replaces setUp(), and state set there can’t leak from one test to the next:

struct SyncTests {
    let api: MockAPI
    let store: LocalStore

    init() async throws {
        api = MockAPI()
        store = try await LocalStore(inMemory: true)
    }

    @Test func pushesPendingChanges() async throws { /* … */ }
    @Test func skipsAlreadySyncedRecords() async throws { /* … */ }
}

The initialiser can be async and throws. If you need teardown, make the suite a final class (or an actor) and use deinit. deinit can’t be async or throwing, which is a real limitation if your tearDown() awaited something. In that case, use defer in the test body.

Tests run in parallel by default

This is the change that most often breaks a migrated suite. XCTest runs the test methods of a class one after another. Swift Testing runs the tests in a suite in parallel, in the same process. Tests that share a singleton, a file on disk, UserDefaults.standard or a global mock will now interfere with each other, usually as a flaky failure that disappears when you run one test alone.

XCTest’s own parallel testing uses separate processes, so a singleton that was safe there may not be safe now. The best fix is to remove the shared state: give each test its own in-memory store or temporary directory. If you can’t yet, mark the suite:

@Suite(.serialized)
struct SettingsTests {
    @Test func defaultsToMetric() { /* … */ }
    @Test func persistsChoice() { /* … */ }
}

.serialized orders the tests within that suite only. Unrelated suites still run alongside it, so it does not protect state shared across suites. Treat it as a stopgap for legacy code.

Tests do not run on the main actor by default

XCTest runs synchronous test methods on the main actor. Swift Testing runs test functions on an arbitrary task. A test that touches UIKit, or a type that is @MainActor, needs the annotation:

@MainActor
struct ProfileViewModelTests {
    @Test func showsPlaceholderBeforeLoad() {
        let model = ProfileViewModel()
        #expect(model.title == "Loading…")
    }
}

The compiler will flag most calls into @MainActor code that lack it.

Async tests and callbacks

If the code under test is async, await it in an async test. No expectation is needed:

@Test func fetchesProfile() async throws {
    let profile = try await ProfileService(client: .stub).load(id: 42)
    #expect(profile.name == "Ada")
}

For an API that reports through a callback or handler, XCTestExpectation becomes a confirmation. The key difference is that a confirmation does not wait. The event must happen before the confirmation closure returns, so the closure has to await the work that triggers it:

// Before
func testReportsEachUpload() async {
    let uploaded = expectation(description: "uploaded")
    uploaded.expectedFulfillmentCount = 3
    uploader.onUpload = { _ in uploaded.fulfill() }
    await uploader.send(files: three)
    await fulfillment(of: [uploaded], timeout: 2)
}
// After
@Test func reportsEachUpload() async {
    await confirmation(expectedCount: 3) { uploaded in
        uploader.onUpload = { _ in uploaded() }
        await uploader.send(files: three)
    }
}

If the callback fires later and send returns first, the confirmation fails. Wrap the callback in a continuation instead. expectedCount also takes a range with a lower bound (10...), which replaces assertForOverFulfill = false, and expectedCount: 0 asserts that something does not happen. There is no timeout argument. If an event may never arrive, the test can hang. Put a timeout in the code under test or in the continuation that wraps it.

Parameterised tests

This is the feature worth migrating for. A loop with several XCTAssert calls reports one failure and hides which input caused it. Pass the inputs as arguments and each one is its own test case, reported separately and run in parallel:

enum Currency: String, CaseIterable { case gbp, eur, usd, jpy }

@Test(arguments: Currency.allCases)
func formatsZero(_ currency: Currency) {
    #expect(Money(0, currency).formatted().contains("0"))
}

@Test(arguments: zip(["SAVE10", "SAVE20", "NONE"], [10, 20, 0]))
func discountPercent(code: String, expected: Int) {
    #expect(Discount.percent(for: code) == expected)
}

Note the zip. With two separate collections, the framework runs every combination (the Cartesian product): passing Currency.allCases and 1...100 gives 400 cases. Use zip when the arguments are pairs. If the arguments conform to protocols such as Encodable or RawRepresentable, you can also re-run a single failing case on its own.

If a table of examples isn’t enough, see our article on property-based testing in TypeScript with fast-check for the generated-input version of the same idea.

Skips and known failures

  • XCTSkipIf and XCTSkipUnless become the traits .disabled(if:) and .enabled(if:) on a test or suite. These are evaluated before the test starts.
  • To end a running test early without a failure, try Test.cancel("reason") replaces throwing XCTSkip. It needs Swift 6.3 (Xcode 26.4) or later.
  • XCTExpectFailure becomes withKnownIssue("reason") { … }. Use isIntermittent: true for the non-strict case. Unlike the closure-less form of XCTExpectFailure, it only covers the code inside the closure, so wrap the failing part and not the whole test.

What to leave in XCTest

Swift Testing has no replacement for UI automation (XCUIApplication) or for performance tests (measure and XCTMetric), and Apple’s XCTest documentation points to XCTest for both. Keep those in XCTest, along with any tests written in Objective-C. Having both frameworks in one test target is supported.

A test suite is part of the product. If you want help moving an app’s tests over, or adding tests to an app that has none, see our iOS app development service.

Have something you'd like built?

Tell us what you're building. We'll reply within two working days with questions, an approach and next steps.

Start a project
Esc

↑ ↓ to move · Enter to open