DEV Community

Dheerendra Chaturvedi
Dheerendra Chaturvedi

Posted on

Swift Testing vs XCTest in 2026: Migrating Real iOS Projects to Modern Testing

Most real iOS projects in 2026 should run both Swift Testing and XCTest: Swift Testing for new and migrated unit tests, and XCTest for UI tests, performance tests, and any code that still interacts with Objective-C.

This article details the differences between the two frameworks and guides you through migrating a production app module piece by piece without rewriting the entire suite. Each code example is from a small Swift package (AuthKit, source on GitHub) that I tested before publishing.

  • Toolchain: Xcode 26.3 (17C529), Swift 6.2.4, Swift 6 language mode.
  • Platforms: macOS, plus the iOS 26.2 and iOS 18.5 simulators.
  • Result: 22 Swift tests (38 test cases once arguments are expanded) and 5 XCTest tests, all in one package with no warnings.

Where a feature needs a particular Swift version, I say so.


1. Introduction

Why test architecture matters

Modern iOS code is concurrent by default. A sign-in flow might involve a @MainActor view model, an actor handling the session, and a Sendable network client—all triggered with a single tap. Swift 6's strict concurrency checking identifies many data races during compilation. The remaining verification is done through your tests, ensuring correct ordering, error handling, and behavior under concurrent calls.

So your tests now need to be concurrency-aware too. A test suite relying on shared mutable state and implicit ordering will either fail to compile under Swift 6 or become flaky.

What XCTest gets right, and where it struggles

XCTest has been the standard since 2013 and is still fully supported. Its strengths include:

  • It is the only option for UI testing (XCUIApplication) and performance testing (measure).
  • It works with Objective-C test code.
  • Every CI system, coverage tool and reporting tool understands it.

Its limitations show in Swift-first code:

  • Tests are discovered via naming convention (func test…) using the Objective-C runtime.
  • There are over 40 assertion functions like XCTAssertEqual, XCTAssertNil, and XCTAssertGreaterThan, each with its own failure message format.
  • There is no built-in parameterized testing. You write loops, and the first failing value hides the rest.
  • XCTAssertThrowsError can't take an async expression.
  • Lifecycle hooks depend on implicitly unwrapped optionals (var sut: Service!), which become a bit cumbersome with Swift 6.

Why Apple introduced Swift Testing

Swift Testing arrived with Xcode 16 (Swift 6.0) in 2024. It's a Swift-native framework based on macros and Swift concurrency.

  • @Test and @Suite declare tests explicitly. No naming conventions.
  • #expect and #require replace the entire XCTAssert family. These macros capture the expression, ensuring that a failure displays the values on both sides.
  • Parameterized tests are built in, and each argument runs as its own test case.
  • Tests run in parallel by default, in-process, using Swift concurrency.
  • Traits (.tags, .timeLimit, .serialized, .enabled(if:), custom traits) attach behavior declaratively.

Why they coexist

Swift Testing does not replace XCTest; it replaces XCTest for unit tests written in Swift. One test target can contain both kinds of test, and swift test, xcodebuild test and Xcode's Test navigator run both together. You migrate when it pays off, file by file.


2. Understanding the architecture

XCTest: classes, the Objective-C runtime and a fixed lifecycle

XCTest finds tests at runtime. It looks for XCTestCase subclasses and their methods whose names start with test. Each test method gets a fresh instance of its class, and the lifecycle around every test looks like this:

class setUp()             ← once per class
  init (new instance)
  setUp() / setUp() async throws
  testSomething()
  addTeardownBlock blocks (last in, first out)
  tearDown() / tearDown() async throws
class tearDown()          ← once per class
Enter fullscreen mode Exit fullscreen mode

Tests within a class run in a fixed order by default; test plans can randomize it. Parallel testing in XCTest is opt-in (in the test plan, or with -parallel-testing-enabled YES). When it's on, Xcode spreads test classes across several runner processes, which on iOS means several simulator clones.

Swift Testing: macros, metadata and tasks

@Test and @Suite are macros that generate metadata at compile time for the test runner. This means you can name your test functions anything you want. The runner uses this metadata to discover and execute the tests.

  1. Collects every test and its traits.
  2. Expands parameterized tests into one test case per argument.
  3. Runs tests and test cases concurrently as Swift tasks in a single process, unless a trait or setting says otherwise.

A suite is just a type: a struct, class, actor or enum. For instance-method tests, the suite is initialized again for every test, so init() plays the role of setUp(). If you need teardown, make the suite a class or actor and use deinit, or wrap tests in a custom scoping trait (shown in section 5).

How both fit into Xcode

XCTest and Swift Testing running side by side in one test target, both reporting into one result bundle

In Xcode 26, both frameworks report into the same Test navigator, test report, and .xcresult bundle. The xcodebuild run in section 9 consolidates XCTest and Swift Testing results into a single summary.


3. XCTest vs Swift Testing

Area XCTest Swift Testing
Test declaration final class X: XCTestCase + func testName() @Test func anyName(), optionally inside a @Suite type
Display names Method name @Test("Human readable name")
Assertions 40+ functions: XCTAssertEqual, XCTAssertTrue, XCTAssertNil, … #expect(expression) for everything; failures show the captured values
Stop on failure XCTUnwrap, or continueAfterFailure = false try #require(expression), which also unwraps optionals
Parameterized tests Not built in: write a loop @Test(arguments:), with zip for paired inputs; each argument is a separate, re-runnable test case
Async/await async test methods; XCTestExpectation + await fulfillment(of:timeout:) async tests; confirmation() for events
Lifecycle Class and instance setUp/tearDown (sync or async), teardown blocks Suite init per test; deinit for classes/actors; TestScoping traits (Swift 6.1+)
Parallel execution Opt-in; runs across processes On by default; runs in-process. .serialized trait opts out
Grouping One class = one group @Suite types, which can nest; tags work across suites
Error handling XCTAssertThrowsError (synchronous only) #expect(throws:) with a type, a specific Equatable error, or Never.self; works with await. It returns the error from Swift 6.1
Conditional and known issues XCTSkip, XCTExpectFailure .enabled(if:), .disabled(), withKnownIssue {}, .bug()
Time limits executionTimeAllowance .timeLimit(.minutes(n))
UI testing ✅ XCUIApplication ❌ Not supported: keep these in XCTest
Performance testing ✅ measure {} ❌ Not supported
Objective-C ✅ ❌ Swift only
Process exit tests ❌ ✅ Swift 6.2+: macOS, Linux and Windows only, not iOS
Migration complexity — Low for pure logic, medium for async or shared-state tests; UI and performance tests stay in XCTest

4. Practical code comparison: the same requirement in both

Requirement: a credential validator and an authentication service. The service checks input, sends a POST auth/login, and maps the response to a Session or a typed error.

The production code (abridged; the full source is in the companion package):

public enum ValidationError: Error, Equatable, Sendable {
    case emptyEmail
    case invalidEmail
    case passwordTooShort(minimum: Int)
}

public struct CredentialValidator: Sendable {
    public let minimumPasswordLength: Int
    public func validate(email: String, password: String) throws(ValidationError) { … }
    public func isValidEmail(_ email: String) -> Bool { … }
}

public enum AuthError: Error, Equatable, Sendable {
    case validation(ValidationError)
    case invalidCredentials
    case network(NetworkError)
    case malformedResponse
}

public struct AuthenticationService: Authenticating {
    public init(client: any NetworkClient, validator: CredentialValidator = CredentialValidator())
    public func signIn(email: String, password: String) async throws -> Session
}
Enter fullscreen mode Exit fullscreen mode

Both test suites utilize the same MockNetworkClient (section 7), which resides in the shared AuthKitTestSupport target.

A. XCTest

import AuthKit
import AuthKitTestSupport
import XCTest

final class AuthenticationServiceXCTests: XCTestCase {
    private var client: MockNetworkClient!
    private var service: AuthenticationService!

    override func setUp() async throws {
        try await super.setUp()
        client = MockNetworkClient()
        service = AuthenticationService(client: client)
    }

    override func tearDown() async throws {
        client = nil
        service = nil
        try await super.tearDown()
    }

    func testSuccessfulSignInReturnsTheSession() async throws {
        await client.stub("auth/login", status: 200, json: Fixtures.sessionJSON)

        let session = try await service.signIn(email: "ada@example.com", password: "correct-horse")

        XCTAssertEqual(session, Fixtures.session)
        let requests = await client.requests
        XCTAssertEqual(requests.count, 1)
        let request = try XCTUnwrap(requests.first)
        XCTAssertEqual(request.method, "POST")
        XCTAssertEqual(request.path, "auth/login")
    }

    func testWrongPasswordThrowsInvalidCredentials() async {
        await client.stub("auth/login", status: 401)

        // XCTAssertThrowsError can't take an async expression, so use do/catch.
        do {
            _ = try await service.signIn(email: "ada@example.com", password: "wrong-password")
            XCTFail("Expected signIn to throw")
        } catch {
            XCTAssertEqual(error as? AuthError, .invalidCredentials)
        }
    }

    func testServerErrorsAreMapped() async {
        for status in [500, 503] {
            await client.stub("auth/login", status: status)
            do {
                _ = try await service.signIn(email: "ada@example.com", password: "correct-horse")
                XCTFail("Expected an error for status \(status)")
            } catch {
                XCTAssertEqual(error as? AuthError, .network(.server(status: status)), "status \(status)")
            }
        }
    }

    func testValidatorRejectsShortPassword() {
        let validator = CredentialValidator()
        XCTAssertTrue(validator.isValidEmail("ada@example.com"))
        XCTAssertThrowsError(try validator.validate(email: "ada@example.com", password: "123")) { error in
            XCTAssertEqual(error as? ValidationError, .passwordTooShort(minimum: 8))
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

B. Swift Testing

import AuthKit
import AuthKitTestSupport
import Foundation
import Testing

@Suite("Authentication service", .tags(.auth, .networking))
struct AuthenticationServiceTests {
    // A fresh mock and service for every test: Swift Testing creates a new
    // instance of the suite struct per test, so init() is your setUp.
    let client = MockNetworkClient()
    let service: AuthenticationService

    init() {
        service = AuthenticationService(client: client)
    }

    @Test func successfulSignInReturnsTheSession() async throws {
        await client.stub("auth/login", status: 200, json: Fixtures.sessionJSON)

        let session = try await service.signIn(email: "ada@example.com", password: "correct-horse")

        #expect(session == Fixtures.session)
        let request = try #require(await client.requests.first)
        #expect(request.method == "POST")
        #expect(request.path == "auth/login")
    }

    @Test("HTTP status maps to the right error", arguments: [
        (401, AuthError.invalidCredentials),
        (500, AuthError.network(.server(status: 500))),
        (503, AuthError.network(.server(status: 503))),
    ])
    func mapsStatusCodes(status: Int, expected: AuthError) async {
        await client.stub("auth/login", status: status)

        await #expect(throws: expected) {
            try await service.signIn(email: "ada@example.com", password: "correct-horse")
        }
    }

    @Test func invalidInputNeverHitsTheNetwork() async {
        await #expect(throws: AuthError.validation(.invalidEmail)) {
            try await service.signIn(email: "ada", password: "correct-horse")
        }
        #expect(await client.requests.isEmpty)
    }
}
Enter fullscreen mode Exit fullscreen mode

And the validator, using parameterized tests:

@Suite("Credential validation", .tags(.auth))
struct CredentialValidatorTests {
    let validator = CredentialValidator(minimumPasswordLength: 8)

    @Test("Rejects malformed emails", arguments: [
        "", "ada", "ada@", "@example.com", "ada@example", "ada@.com", "ada@example.", "a da@example.com",
    ])
    func rejectsInvalidEmail(_ email: String) {
        #expect(!validator.isValidEmail(email))
    }

    @Test("Maps each bad input to the right error", arguments: zip(
        ["", "not-an-email", "ada@example.com"],
        [ValidationError.emptyEmail, .invalidEmail, .passwordTooShort(minimum: 8)]
    ))
    func reportsTheRightError(email: String, expected: ValidationError) {
        #expect(throws: expected) {
            try validator.validate(email: email, password: "short")
        }
    }

    @Test func thrownErrorCanBeInspected() throws {
        // Swift 6.1+: #expect(throws:) returns the error it caught
        let error = #expect(throws: ValidationError.self) {
            try validator.validate(email: "ada@example.com", password: "123")
        }
        #expect(error == .passwordTooShort(minimum: 8))
    }
}
Enter fullscreen mode Exit fullscreen mode

What changed

XCTest Swift Testing Why it matters
final class …: XCTestCase struct with @Suite A value type with let properties: no shared mutable state between tests, and no ! optionals.
setUp() assigns client, service init() (or property initializers) A new suite instance per test gives the same isolation, with immutability the compiler checks.
tearDown() sets properties to nil nothing The instance is simply released. Use deinit or a scoping trait only for real cleanup (files, servers).
func testSuccessful… @Test func successful… The macro, not a name prefix, marks the test. @Test("…") adds a readable name for reports.
XCTAssertEqual(a, b) #expect(a == b) One macro for every comparison. A failure prints both values, e.g. session → Session(…) == Fixtures.session → Session(…).
try XCTUnwrap(x) try #require(x) Same idea: unwrap or stop the test. #require also accepts Boolean conditions.
do { …; XCTFail() } catch { XCTAssertEqual(error as? …) } await #expect(throws: expected) { try await … } Async error checks in one line, without casting.
for status in [500, 503] { … } @Test(arguments:) Each status becomes its own test case: all of them run, failures are reported separately, and you can re-run a single argument in Xcode.
Implicit order within a class Parallel, no guaranteed order Each test must be independent. The struct-per-test design enforces most of that for you.

5. Advanced Swift Testing

Every API below compiled and ran on Swift 6.2.4. Minimum versions noted where they are above 6.0.

Parameterized tests: one list, or pairs

  • arguments: collection runs the test once per element.
  • arguments: zip(a, b) pairs elements by position.
  • arguments: a, b (two collections) runs every combination. Use it with care: 10 × 10 inputs means 100 test cases.
@Test("Shows a readable message for each failure", arguments: [
    (AuthError.network(.offline), "You're offline. Check your connection and try again."),
    (AuthError.validation(.passwordTooShort(minimum: 8)), "Password must be at least 8 characters."),
    (AuthError.malformedResponse, "Something went wrong. Please try again."),
])
func errorMessages(error: AuthError, message: String) async { … }
Enter fullscreen mode Exit fullscreen mode

Arguments must be Sendable. If they also conform to Codable or Identifiable, Xcode can re-run a single failing case.

Async and concurrent tests

This test fires five concurrent sign-ins at an actor and proves that only one network request goes out. That kind of guarantee is easy to get wrong and hard to test any other way:

@Test(.timeLimit(.minutes(1)))
func concurrentSignInsShareOneRequest() async throws {
    // The delay keeps the first request in flight while the others arrive.
    let client = MockNetworkClient(delay: .milliseconds(200))
    await client.stub("auth/login", status: 200, json: Fixtures.sessionJSON)
    let repository = UserRepository(auth: AuthenticationService(client: client), store: InMemorySessionStore())

    let users = try await withThrowingTaskGroup(of: User.self) { group in
        for _ in 0..<5 {
            group.addTask {
                try await repository.signIn(email: "ada@example.com", password: "correct-horse")
            }
        }
        return try await group.reduce(into: []) { $0.append($1) }
    }

    #expect(users.count == 5)
    #expect(users.allSatisfy { $0 == Fixtures.user })
    #expect(await client.requests.count == 1)
}
Enter fullscreen mode Exit fullscreen mode

.timeLimit uses minutes as its unit and serves as a safeguard against hangs, not as a performance assertion.

Test isolation

  • Per-test state: The suite is re-created for each test, ensuring that let properties are never shared between tests.
  • Actor isolation: Mark a suite with @MainActor to test main-actor types like view models. Each test in this suite runs on the main actor, making the code resemble the call sites in your app.
@MainActor
@Suite("Login view model", .tags(.auth))
struct LoginViewModelTests {
    let client = MockNetworkClient()
    let viewModel: LoginViewModel

    init() {
        let repository = UserRepository(
            auth: AuthenticationService(client: client),
            store: InMemorySessionStore()
        )
        viewModel = LoginViewModel(repository: repository)
    }

    @Test func submitIsDisabledUntilTheFormIsValid() {
        #expect(!viewModel.canSubmit)
        viewModel.email = "ada@example.com"
        #expect(!viewModel.canSubmit)
        viewModel.password = "correct-horse"
        #expect(viewModel.canSubmit)
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Opting out of parallelism: @Suite(.serialized) runs the suite's tests (and parameterized cases) sequentially. Use this as a transitional measure for legacy code that interacts with a global state. It masks the shared state issue but doesn't resolve it.

Confirmations: testing events and callbacks

confirmation() replaces XCTestExpectation for events. There is one key difference: it does not wait. The event must happen before the closure returns, so await the work inside the closure.

@Test func successfulSignInNotifiesOnce() async {
    await client.stub("auth/login", status: 200, json: Fixtures.sessionJSON)
    viewModel.email = "ada@example.com"
    viewModel.password = "correct-horse"

    await confirmation("onSignedIn is called") { signedIn in
        viewModel.onSignedIn = { user in
            #expect(user == Fixtures.user)
            signedIn()
        }
        await viewModel.signIn()
    }
    #expect(viewModel.state == .signedIn(Fixtures.user))
}

@Test func failedSignInNeverNotifies() async {
    await client.stub("auth/login", status: 401)
    viewModel.email = "ada@example.com"
    viewModel.password = "wrong-password"

    await confirmation("onSignedIn is not called", expectedCount: 0) { signedIn in
        viewModel.onSignedIn = { _ in signedIn() }
        await viewModel.signIn()
    }
    #expect(viewModel.state == .failed(message: "Email or password is incorrect."))
}
Enter fullscreen mode Exit fullscreen mode
  • expectedCount: 0 asserts something never happens. XCTest needs isInverted and a timeout for that.
  • From Swift 6.1, expectedCount also accepts a range, such as 1....
  • If your callback API lacks a "done" point to await (for instance, a NotificationCenter post on another queue), wrap it in an AsyncStream and await it inside the closure. Alternatively, keep the test in XCTest, where fulfillment(of:timeout:) will wait for it.

Error validation

There are three forms, all usable with await:

#expect(throws: AuthError.invalidCredentials) { … }   // this exact error (Equatable)
#expect(throws: ValidationError.self) { … }          // any error of this type
#expect(throws: Never.self) { … }                    // must not throw
Enter fullscreen mode Exit fullscreen mode

Starting from Swift 6.1, the type form returns the caught error, allowing you to inspect it (see thrownErrorCanBeInspected above).

Custom traits: replacing setUp/tearDown with something reusable

A trait conforming to TestScoping (Swift 6.1+) encapsulates each test it's applied to. Specifically, it provides each test with its own temporary directory and ensures it gets deleted afterward.

struct TemporaryDirectoryTrait: TestTrait, SuiteTrait, TestScoping {
    @TaskLocal static var current: URL?

    // On a suite, apply the scope to every test inside it, not once for the whole suite.
    var isRecursive: Bool { true }

    func provideScope(
        for test: Test,
        testCase: Test.Case?,
        performing function: @Sendable () async throws -> Void
    ) async throws {
        // Suites call this too; only tests need a directory.
        guard !test.isSuite else { return try await function() }
        let directory = FileManager.default.temporaryDirectory
            .appending(path: "AuthKitTests-\(UUID().uuidString)")
        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
        defer { try? FileManager.default.removeItem(at: directory) }
        try await Self.$current.withValue(directory) {
            try await function()
        }
    }
}

extension Trait where Self == TemporaryDirectoryTrait {
    static var temporaryDirectory: Self { Self() }
}
Enter fullscreen mode Exit fullscreen mode

Using it:

@Suite("File session store", .tags(.persistence), .temporaryDirectory)
struct FileSessionStoreTests {
    let store: FileSessionStore

    init() throws {
        let directory = try #require(TemporaryDirectoryTrait.current)
        store = FileSessionStore(directory: directory)
    }

    @Test func savedSessionRoundTrips() async throws {
        try await store.save(Fixtures.session)
        #expect(try await store.load() == Fixtures.session)
    }
}
Enter fullscreen mode Exit fullscreen mode

Two details catch people out:

  • isRecursive: without it, a suite-level trait wraps the suite once, so all its tests would share one directory.
  • @TaskLocal: This is how trait tests pass values to the tests. It's safe with parallel tests since each test runs in its own task.

Tags

Tags are declared once and can be applied anywhere:

extension Tag {
    @Tag static var auth: Self
    @Tag static var networking: Self
    @Tag static var persistence: Self
}
Enter fullscreen mode Exit fullscreen mode

In Xcode, you can group tests by tag in the Test navigator and include or exclude tags in a test plan. For command-line filtering, use name-based filtering (section 9). swift test and xcodebuild lack a tag filter flag.

Dependency injection, actors and Sendable

Everything above depends on one production-code decision: dependencies come in through Sendable protocols in the initializer. Section 7 shows the full set of types.


6. Real-world migration strategy

Take a typical app:

MyApplication/
  Sources/
    Authentication/
    Networking/
    Database/
    ViewModels/
  Tests/
    AuthenticationTests/      ← XCTest unit tests
    NetworkingTests/          ← XCTest unit tests, some async
    ViewModelTests/           ← XCTest, lots of XCTestExpectation
    UITests/                  ← XCUITest
Enter fullscreen mode Exit fullscreen mode

Step 1: audit the existing suite

Count what you have before deciding anything:

# Test classes and test methods per folder
grep -rl "XCTestCase" Tests | xargs -n1 dirname | sort | uniq -c
grep -rE "func test[A-Z]" Tests | cut -d/ -f2 | sort | uniq -c

# Things that need care when migrating
grep -rnE "XCTestExpectation|expectation\(description" Tests   # callbacks
grep -rnE "measure(Metrics)?\s*[\({]" Tests                    # performance tests: stay in XCTest
grep -rnE "XCUIApplication" Tests                              # UI tests: stay in XCTest
grep -rnE "static var|class var|\.shared" Tests                # shared state: refactor before migrating
Enter fullscreen mode Exit fullscreen mode

Step 2: pick the first tests to migrate

Good first candidates:

  • Pure logic tests include validators, formatters, mappers, and reducers. These are straightforward to implement.
  • Tests that loop over inputs become parameterized, providing clearer failure reports.
  • Async tests that use the do/catch + XCTFail pattern. These become a single #expect(throws:).

Migrate later, or never:

  • Tests built around XCTestExpectation with timeouts on APIs you can't await. Convert them only once the code under test has an async API.
  • Tests that rely on order or on class setUp() shared fixtures. Fix the isolation first.

Step 3: keep UI and performance tests in XCTest

Swift Testing has no XCUIApplication and no measure. Leave UITests/ as it is:

// UITests/LoginUITests.swift: stays XCTest
final class LoginUITests: XCTestCase {
    @MainActor
    func testSignInShowsHome() {
        let app = XCUIApplication()
        app.launchArguments = ["-uiTesting"]
        app.launch()

        app.textFields["Email"].tap()
        app.textFields["Email"].typeText("ada@example.com")
        app.secureTextFields["Password"].tap()
        app.secureTextFields["Password"].typeText("correct-horse")
        app.buttons["Sign In"].tap()

        XCTAssertTrue(app.staticTexts["Welcome, Ada"].waitForExistence(timeout: 5))
    }
}
Enter fullscreen mode Exit fullscreen mode

(This snippet is illustrative: it needs an app target, so it isn't part of the verified sample package.)

Step 4: convert one test case class at a time

Here's a mechanical checklist for each XCTestCase class:

  1. Replace import XCTest with import Testing, or keep both while the file is mid-migration.
  2. Change final class FooTests: XCTestCase to struct FooTests. Add @Suite("…") if you want a display name or traits.
  3. Move setUp() work into init() (it can be async throws), and turn var x: T! into let x: T.
  4. Delete tearDown() if it only nils out properties. Move real cleanup to deinit (on a final class suite) or a scoping trait.
  5. Change func testFoo() to @Test func foo().
  6. Replace each assertion:
    • XCTAssertEqual(a, b) → #expect(a == b)
    • XCTAssertTrue(x) → #expect(x); XCTAssertFalse(x) → #expect(!x)
    • XCTAssertNil(x) → #expect(x == nil)
    • try XCTUnwrap(x) → try #require(x)
    • XCTFail("…") → Issue.record("…")
    • XCTAssertThrowsError → #expect(throws:)
    • XCTestExpectation → confirmation(), or plain await
  7. Turn input loops into @Test(arguments:).
  8. Run the file. Then run it again with the scheme's parallel testing enabled.

Step 5: introduce Swift Testing incrementally

You don't need a new target. Xcode 16 and later, and SwiftPM 6, run both frameworks from the same test target. One file can even contain both kinds of test. In a package, depending on how you organize, add a test target or just add files:

// swift-tools-version: 6.0
targets: [
    .target(name: "AuthKit"),
    // Mocks and fixtures shared by both test targets
    .target(name: "AuthKitTestSupport", dependencies: ["AuthKit"], path: "Tests/AuthKitTestSupport"),
    // Swift Testing and XCTest live side by side
    .testTarget(name: "AuthKitTests", dependencies: ["AuthKit", "AuthKitTestSupport"]),
    .testTarget(name: "AuthKitXCTests", dependencies: ["AuthKit", "AuthKitTestSupport"]),
]
Enter fullscreen mode Exit fullscreen mode

Move mocks and fixtures into a support target, as above, so that migrated and unmigrated tests share them. The support target imports neither XCTest nor Testing, so either framework can use it.

Step 6: run both frameworks together, but never mix their assertions

This is the most important rule in the whole migration, and I verified it on Swift 6.2.4. A failing assertion from the "other" framework is silently ignored:

@Test func xctAssertInsideSwiftTesting() { XCTAssertEqual(f(), 2) }          // f() returns 1: test PASSES
final class Mixed: XCTestCase { func testExpectInsideXCTest() { #expect(f() == 2) } }  // test PASSES
Enter fullscreen mode Exit fullscreen mode

Both of those tests reported passed. A half-converted file can therefore turn your red tests green without anyone noticing. Convert a test's assertions together with its declaration, in the same change. A quick check to run in CI:

# @Test functions must not call XCTAssert*, and XCTestCase files must not use #expect/#require
grep -rlE "@Test" Tests | xargs grep -nE "XCTAssert|XCTFail|XCTUnwrap" && exit 1
grep -rlE "XCTestCase" Tests | xargs grep -nE "#expect|#require" && exit 1
Enter fullscreen mode Exit fullscreen mode

These checks work per file, so they give false alarms only if you deliberately keep both kinds of test in one file. Don't do that for long.

Step 7: validate CI

Run the full suite in CI on the same Xcode version developers use, and compare test counts before and after each migration PR. Remember that parameterized tests report test cases as well as tests: this sample package has 22 Swift Testing tests that expand to 38 test cases. A count that drops unexpectedly means a test stopped being discovered. That's how a missing @Test shows up.

Step 8: watch for flakiness and concurrency issues

Migrated tests now run in parallel, in one process. Code that "worked" under XCTest's serial default can start failing in Swift Testing:

  • singletons (URLSession.shared with a stubbed URLProtocol, UserDefaults.standard, a shared Core Data stack)
  • global caches and feature flags
  • fixed file paths in the temporary directory

Fix them with injection, per-test instances or scoping traits. Use .serialized only as a temporary marker, with a comment explaining why. Section 9 shows how to find flaky tests in CI.


7. Production-level testing example

The full sample package, AuthKit:

swift-testing-demo/
  Package.swift
  Sources/AuthKit/
    CredentialValidator.swift
    NetworkClient.swift          ← NetworkClient protocol + URLSessionNetworkClient
    AuthenticationService.swift
    SessionStore.swift           ← FileSessionStore, InMemorySessionStore
    UserRepository.swift         ← actor
    LoginViewModel.swift         ← @MainActor @Observable
  Tests/
    AuthKitTestSupport/          ← MockNetworkClient, Fixtures (no test framework import)
    AuthKitTests/                ← Swift Testing
    AuthKitXCTests/              ← XCTest
Enter fullscreen mode Exit fullscreen mode

NetworkClient: the seam

public protocol NetworkClient: Sendable {
    func send(_ request: HTTPRequest) async throws -> (data: Data, status: Int)
}

/// Production implementation. Tests never touch it.
public struct URLSessionNetworkClient: NetworkClient {
    private let baseURL: URL
    private let session: URLSession

    public init(baseURL: URL, session: URLSession = .shared) { … }

    public func send(_ request: HTTPRequest) async throws -> (data: Data, status: Int) {
        var urlRequest = URLRequest(url: baseURL.appending(path: request.path))
        urlRequest.httpMethod = request.method
        urlRequest.httpBody = request.body
        urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        do {
            let (data, response) = try await session.data(for: urlRequest)
            return (data, (response as? HTTPURLResponse)?.statusCode ?? 0)
        } catch let error as URLError where error.code == .notConnectedToInternet {
            throw NetworkError.offline
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

MockNetworkClient: an actor, not an @unchecked Sendable class

/// An actor, so tests running in parallel can't race on `requests`.
public actor MockNetworkClient: NetworkClient {
    private var responses: [String: Result<(data: Data, status: Int), any Error>] = [:]
    public private(set) var requests: [HTTPRequest] = []
    private let delay: Duration

    public init(delay: Duration = .zero) {
        self.delay = delay
    }

    public func stub(_ path: String, status: Int, json: String = "{}") {
        responses[path] = .success((Data(json.utf8), status))
    }

    public func stub(_ path: String, error: any Error) {
        responses[path] = .failure(error)
    }

    public func send(_ request: HTTPRequest) async throws -> (data: Data, status: Int) {
        requests.append(request)
        if delay > .zero { try await Task.sleep(for: delay) }
        guard let response = responses[request.path] else {
            throw NetworkError.server(status: 404)
        }
        return try response.get()
    }
}
Enter fullscreen mode Exit fullscreen mode

An actor can satisfy the async protocol requirement directly, and recording requests is free of data races. The usual Swift 6 shortcut, final class MockNetworkClient: @unchecked Sendable with a var requests, compiles but is a data race once tests run in parallel.

AuthenticationService

public struct AuthenticationService: Authenticating {
    private let client: any NetworkClient
    private let validator: CredentialValidator

    public init(client: any NetworkClient, validator: CredentialValidator = CredentialValidator()) {
        self.client = client
        self.validator = validator
    }

    public func signIn(email: String, password: String) async throws -> Session {
        do {
            try validator.validate(email: email, password: password)
        } catch {
            throw AuthError.validation(error)
        }

        let body = try JSONEncoder().encode(["email": email, "password": password])
        let response: (data: Data, status: Int)
        do {
            response = try await client.send(HTTPRequest(method: "POST", path: "auth/login", body: body))
        } catch let error as NetworkError {
            throw AuthError.network(error)
        }

        switch response.status {
        case 200:
            guard let session = try? JSONDecoder().decode(Session.self, from: response.data) else {
                throw AuthError.malformedResponse
            }
            return session
        case 401:
            throw AuthError.invalidCredentials
        default:
            throw AuthError.network(.server(status: response.status))
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

validate uses typed throws (throws(ValidationError)), so error in the first catch is already a ValidationError, with no cast needed.

UserRepository: an actor that coalesces requests

public actor UserRepository {
    private let auth: any Authenticating
    private let store: any SessionStore
    private var inFlight: Task<Session, any Error>?

    public private(set) var currentUser: User?

    public init(auth: any Authenticating, store: any SessionStore) { … }

    /// A second tap on "Sign in" while a request is running joins that request
    /// instead of sending another one.
    public func signIn(email: String, password: String) async throws -> User {
        if let inFlight {
            return try await inFlight.value.user
        }
        let task = Task { [auth] in try await auth.signIn(email: email, password: password) }
        inFlight = task
        defer { inFlight = nil }

        let session = try await task.value
        try await store.save(session)
        currentUser = session.user
        return session.user
    }

    public func restore() async throws -> User? { … }
    public func signOut() async throws { … }
}
Enter fullscreen mode Exit fullscreen mode

Actor reentrancy is the reason this works: while the first call is suspended at await task.value, the other callers enter the actor, find inFlight set, and join that task. concurrentSignInsShareOneRequest (section 5) proves it.

LoginViewModel

@MainActor
@Observable
public final class LoginViewModel {
    public enum State: Equatable {
        case idle
        case loading
        case signedIn(User)
        case failed(message: String)
    }

    public var email = ""
    public var password = ""
    public private(set) var state: State = .idle
    public var onSignedIn: ((User) -> Void)?

    public func signIn() async {
        guard state != .loading else { return }
        state = .loading
        do {
            let user = try await repository.signIn(email: email, password: password)
            state = .signedIn(user)
            onSignedIn?(user)
        } catch {
            state = .failed(message: Self.message(for: error))
        }
    }
    …
}
Enter fullscreen mode Exit fullscreen mode

The repository's Swift Testing suite

@Suite("User repository", .tags(.auth))
struct UserRepositoryTests {
    @Test func signInStoresTheSession() async throws {
        let client = MockNetworkClient()
        await client.stub("auth/login", status: 200, json: Fixtures.sessionJSON)
        let store = InMemorySessionStore()
        let repository = UserRepository(auth: AuthenticationService(client: client), store: store)

        let user = try await repository.signIn(email: "ada@example.com", password: "correct-horse")

        #expect(user == Fixtures.user)
        #expect(await repository.currentUser == Fixtures.user)
        #expect(try await store.load() == Fixtures.session)
    }

    @Test func failedSignInLeavesNoUser() async {
        let client = MockNetworkClient()
        await client.stub("auth/login", status: 401)
        let repository = UserRepository(auth: AuthenticationService(client: client), store: InMemorySessionStore())

        await #expect(throws: AuthError.invalidCredentials) {
            try await repository.signIn(email: "ada@example.com", password: "wrong-password")
        }
        #expect(await repository.currentUser == nil)
    }
}
Enter fullscreen mode Exit fullscreen mode

For the view model's error messages, there's an even smaller stub, a protocol conformance in four lines:

/// A tiny protocol-based stub: no network, no JSON.
private struct FailingAuth: Authenticating {
    let error: AuthError
    func signIn(email: String, password: String) async throws -> Session { throw error }
}
Enter fullscreen mode Exit fullscreen mode

Here's how the pieces fit:

AuthKit dependency graph: view model, actor repository, and protocol seams with production and test implementations

None of the tests touch the network or a real server. Production code never imports a test framework, and test-only types live in the test targets.


8. Common migration mistakes

1. Migrating XCUITests. They can't be migrated: Swift Testing has no UI-automation API. The same goes for measure {} performance tests. Leave both in XCTest without guilt.

2. Mixing assertions across frameworks. As shown in section 6, on Swift 6.2.4 XCTAssert… inside @Test, and #expect inside XCTestCase, don't fail the test. That's the most dangerous half-finished migration state. Lint for it.

3. Incorrect actor isolation.

  • Accessing a @MainActor view model from a test that isn't on the main actor won't compile in Swift 6. Mark the suite or test @MainActor; don't sprinkle MainActor.run everywhere.
  • The other way round, putting @MainActor on every suite "just to make it compile" makes all those tests share the main actor, so they no longer run in parallel. Isolate only the suites that test main-actor code.

4. Shared mutable test state.

  • static var fixtures, singletons and "let shared = Mock() at file scope" are tolerable when tests run serially. With parallel tests they're data races.
  • Swift 6 flags most of them (static var isn't concurrency-safe). The fix is per-test instances: suite properties, init() or a scoping trait. It isn't nonisolated(unsafe).

5. Non-Sendable test dependencies.

  • Parameterized arguments and anything captured by concurrent tasks must be Sendable. Make mocks actors, or value types, or protect their state properly.
  • @unchecked Sendable on a class with var state hides the error the compiler correctly reported.

6. Assuming execution order.

  • XCTest runs a class's tests in a stable order by default. Some suites quietly depend on test1_login running before test2_fetchProfile.
  • Swift Testing makes no order guarantee. Even within a .serialized suite, each test still gets a fresh suite instance, so state doesn't carry over.
  • Each test must set up everything it needs.

7. Overusing setup and teardown.

  • Moving a 40-line setUp() into init() unchanged keeps the original problem: every test pays for fixtures it doesn't use, and readers can't see what matters.
  • Prefer small factory helpers that each test calls with the values it cares about, as UserRepositoryTests does.

8. Mixing lifecycle assumptions.

  • XCTest's class func setUp() runs once per class. A Swift Testing suite has no direct equivalent: init() runs per test, and a scoping trait on a suite runs once (or per test with isRecursive).
  • XCTest's addTeardownBlock runs before tearDown(); in Swift Testing, cleanup belongs in deinit or a trait.
  • Pick one model per suite, and don't count on deinit timing in a struct suite. Structs don't have one.

9. Treating confirmation() like an expectation. It doesn't wait. If the event fires after the closure returns (on a background queue, say), the confirmation fails with "expected 1, got 0". Await the work inside the closure. For fire-and-forget APIs, keep XCTestExpectation or add an awaitable API.


9. CI/CD integration

All commands below were run against the sample package on Xcode 26.3.

Running tests locally and on macOS CI

# Runs XCTest and Swift Testing together
swift test

# Filter by suite or test name (regex); --skip excludes
swift test --filter CredentialValidatorTests --skip thrownErrorCanBeInspected

# JUnit XML for CI dashboards
swift test --xunit-output build/junit.xml
Enter fullscreen mode Exit fullscreen mode

With --xunit-output, each framework writes its own file:

  • Swift Testing writes junit-swift-testing.xml next to the path you give.
  • XCTest results go to the path itself.

Upload both.

Running on iOS simulators with xcodebuild

For a Swift package, list schemes with xcodebuild -list. A package with one product gets a scheme named after it (AuthKit here). A package with several products gets a <Name>-Package scheme.

xcodebuild test \
  -scheme AuthKit \
  -destination 'platform=iOS Simulator,name=iPhone 17,OS=26.2' \
  -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.5' \
  -resultBundlePath TestResults.xcresult
Enter fullscreen mode Exit fullscreen mode
  • Multiple destinations run concurrently. xcodebuild notes that tests then can't also run in parallel within each destination. Add -disable-concurrent-destination-testing if you'd rather run destinations one after another with in-destination parallelism.
  • The destination must exist. If xcodebuild says it can't find a matching device, run xcrun simctl list devices available and check that the runtime is installed. The device name alone can be ambiguous across runtimes, so pin OS=.

Selecting tests works for both frameworks. Swift Testing identifiers include the argument labels:

xcodebuild test -scheme AuthKit \
  -destination 'platform=iOS Simulator,name=iPhone 17,OS=26.2' \
  -only-testing:'AuthKitTests/CredentialValidatorTests' \
  -skip-testing:'AuthKitTests/CredentialValidatorTests/thrownErrorCanBeInspected()' \
  -only-testing:'AuthKitXCTests/AuthenticationServiceXCTests/testServerErrorsAreMapped'
Enter fullscreen mode Exit fullscreen mode

Collecting results

# Totals per device as JSON (Xcode 16+ xcresulttool syntax)
xcrun xcresulttool get test-results summary --path TestResults.xcresult --compact

# Full test tree, including each parameterized case
xcrun xcresulttool get test-results tests --path TestResults.xcresult
Enter fullscreen mode Exit fullscreen mode

For the two-simulator run above, the summary reported "result":"Passed", 42 passing test runs per device, and the statistic "5 tests ran with dynamic parameters": the Swift Testing parameterized tests.

GitHub Actions

GitHub's macos-26 runner image ships Xcode 26. The default Xcode version and the installed simulators change between image releases, so the workflow prints the toolchain, and device names should match the image's README.

{% raw %}
name: Tests

on:
  pull_request:
  push:
    branches: [main]

jobs:
  test:
    runs-on: macos-26
    strategy:
      fail-fast: false
      matrix:
        destination:
          - "platform=iOS Simulator,name=iPhone 17"
          - "platform=iOS Simulator,name=iPhone 16e"
    steps:
      - uses: actions/checkout@v4

      - name: Toolchain
        run: |
          xcodebuild -version
          swift --version

      - name: Test
        run: |
          xcodebuild test \
            -scheme AuthKit \
            -destination "${{ matrix.destination }}" \
            -resultBundlePath TestResults.xcresult

      - name: Summary
        if: always()
        run: xcrun xcresulttool get test-results summary --path TestResults.xcresult --compact

      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: test-results-${{ strategy.job-index }}
          path: TestResults.xcresult

  test-macos:
    runs-on: macos-26
    steps:
      - uses: actions/checkout@v4
      - run: swift test --xunit-output junit.xml
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: junit
          path: junit*.xml
{% endraw %}
Enter fullscreen mode Exit fullscreen mode

To pin an exact Xcode, add sudo xcode-select -s /Applications/Xcode_<version>.app before testing, using a path listed in the runner image's README.

Finding flaky tests

Retries keep the pipeline green, but they hide flakiness, so use two separate jobs:

# PR builds: retry a failing test up to 3 times (the retries are recorded in the .xcresult)
xcodebuild test -scheme AuthKit -destination '…' \
  -retry-tests-on-failure -test-iterations 3 \
  -resultBundlePath TestResults.xcresult

# Nightly: hammer the suite to surface flakiness
xcodebuild test -scheme AuthKit -destination '…' \
  -run-tests-until-failure -test-iterations 50
Enter fullscreen mode Exit fullscreen mode
  • Swift Testing's parallelism makes order- and timing-dependent bugs more likely to show up, which is what you want: you find them in CI rather than in production.
  • When a test only fails under parallelism, the culprit is almost always shared state (section 8, mistake 4).
  • Tests that wait on wall-clock time, such as the delay in MockNetworkClient, can also be slow on loaded CI machines. Keep delays short, assert on behaviour rather than timing, and give hang-prone tests a .timeLimit.

10. Conclusion

Use Swift Testing for:

  • every new unit and integration test written in Swift
  • logic with many input combinations (parameterized tests)
  • async code, actors and @MainActor types
  • tests that benefit from tags, conditional traits or reusable scoping traits

Keep XCTest for:

  • UI tests (XCUIApplication)
  • performance tests (measure)
  • Objective-C test code
  • callback-based tests on APIs you can't await yet, where XCTestExpectation's waiting is genuinely useful
  • stable legacy tests that nobody touches: migrating them adds risk and no value

Use both together (the realistic default in 2026):

  • Run both from the same targets and the same CI job.
  • Migrate a file when you're already changing it, or when a loop becomes a parameterized test.
  • Never let a test use the other framework's assertions.
  • Watch the per-run test and test-case counts in CI.

Neither framework is going away. Swift Testing is where Apple and the Swift project are adding new testing features (exit tests and attachments arrived in Swift 6.2). XCTest remains the foundation for UI automation and performance testing on Apple platforms. Treat migration as ordinary maintenance, not a rewrite project.


Version notes

Feature Minimum
Swift Testing (@Test, @Suite, #expect, #require, traits, confirmation) Swift 6.0 / Xcode 16
#expect(throws:) returning the error, range expectedCount, TestScoping custom traits Swift 6.1 / Xcode 16.3
Exit tests (#expect(processExitsWith:)), attachments Swift 6.2 / Xcode 26. Exit tests are not available when building for iOS: verified, they fail to compile for the iOS simulator
.timeLimit iOS 16 / macOS 13 at runtime

The sample package targets iOS 17 / macOS 14 because LoginViewModel uses @Observable. The testing code itself has no such requirement.

Run the sample yourself

git clone https://github.com/eeshuu/swift-testing-demo
cd swift-testing-demo
swift test
xcodebuild test -scheme AuthKit -destination 'platform=iOS Simulator,name=iPhone 17'
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)