Frameworks

Apple Details Step-by-Step Migration from XCTest to Swift Testing

Still writing Swift tests with XCTest? Apple's guide shows how to move to Swift Testing one step at a time, with before-and-after examples for every common task.

Apple step-by-step guide for migrating from XCTest to Swift Testing
Apple's guide maps familiar XCTest patterns to their Swift Testing equivalents.

Apple has published a step-by-step guide for moving existing tests from XCTest to Swift Testing. Swift Testing offers much of the same power as XCTest, but it uses its own syntax to declare tests and groups of tests.

The guide is practical. For each task, it shows the old XCTest code and the new Swift Testing code side by side.

Step 1: Change the import

The two libraries live in different modules. Instead of XCTest, you import Testing:

// Before
import XCTest

// After
import Testing

A single file can contain tests from both libraries. If it does, import both modules.

Step 2: Use interoperability

Interoperability lets XCTest assertions work inside Swift Testing, and Swift Testing expectations work inside XCTest. That means you can share test helper functions between both kinds of tests. You can also replace XCTAssert() with #expect in your old tests and get the new benefits right away, while you migrate the rest at your own pace.

Apple calls a problem reported by one library inside the other a cross-library issue. For example, a helper that uses XCTAssertEqual and is called from a Swift Testing test creates one. Without interoperability, that test could pass even though the helper's check failed.

Interoperability modes

  • none: interoperability is off, and cross-library issues are ignored.
  • limited: Swift Testing issues keep their severity. XCTest issues become warnings with modernization hints.
  • complete: all cross-library issues keep their original severity, with modernization hints for XCTest ones.
  • strict: XCTest issues are reported with a fatalError.

The default mode depends on your toolchain and the swift-tools-version in your package:

  • Toolchain below 6.4: none.
  • Toolchain 6.4 or later with swift-tools-version below 6.4: limited.
  • Toolchain 6.4 or later with swift-tools-version 6.4 or later: complete.

To pick a mode yourself, set the SWIFT_TESTING environment variable to the mode name before you run tests.

Step 3: Turn test classes into suites

XCTest groups tests in classes that inherit from XCTestCase. Swift Testing does not need that. Test functions can be free functions or members of any Swift type, and a type that groups them is called a suite.

To convert, remove the XCTestCase inheritance. Apple suggests using a struct or an actor instead of a class, because it helps the compiler check concurrency safety.

// Before
class FoodTruckTests: XCTestCase { ... }

// After
struct FoodTruckTests { ... }

Step 4: Replace setUp and tearDown

Instead of setUp() and tearDown(), implement init() and, if needed, deinit. Using async and throws is optional. If you need teardown, make the suite a class or actor, because only those can have deinit.

// Before
class FoodTruckTests: XCTestCase {
  var batteryLevel: NSNumber!
  override func setUp() async throws { batteryLevel = 100 }
  override func tearDown() { batteryLevel = 0 }
}

// After
final class FoodTruckTests {
  var batteryLevel: NSNumber
  init() async throws { batteryLevel = 100 }
  deinit { batteryLevel = 0 }
}

Step 5: Mark test functions with @Test

In XCTest, a test method must be in a test class and its name must start with test. In Swift Testing, any function marked with the @Test attribute is a test, whatever its name.

// Before
func testEngineWorks() { ... }

// After
@Test func engineWorks() { ... }

Tests can still be async, throws, or both, and can be tied to a global actor. One difference: XCTest runs synchronous tests on the main actor by default, while Swift Testing runs every test on an arbitrary task. If a test must run on the main thread, mark it with the main actor.

Step 6: Swap assertions for #expect and #require

XCTest has about 40 XCTAssert functions. Swift Testing replaces them with two macros:

  • #expect records a failure if the condition is false, and the test keeps running.
  • #require throws an error if the condition is false, so the test stops there.
// Before
XCTAssertNotNil(engine.parts.first)
XCTAssertGreaterThan(engine.batteryLevel, 0)
XCTAssertTrue(engine.isRunning)

// After
try #require(engine.parts.first != nil)
#expect(engine.batteryLevel > 0)
#expect(engine.isRunning)

Quick conversion table

  • XCTAssert(x) / XCTAssertTrue(x) becomes #expect(x).
  • XCTAssertFalse(x) becomes #expect(!x).
  • XCTAssertNil(x) / XCTAssertNotNil(x) becomes #expect(x == nil) / #expect(x != nil).
  • XCTAssertEqual(x, y) becomes #expect(x == y), and the greater and less-than versions use >, >=, <, and <=.
  • XCTAssertIdentical(x, y) becomes #expect(x === y).
  • XCTAssertThrowsError(try f()) becomes #expect(throws: (any Error).self) { try f() }.
  • XCTAssertNoThrow(try f()) becomes #expect(throws: Never.self) { try f() }.
  • try XCTUnwrap(x) becomes try #require(x).
  • XCTFail("...") becomes Issue.record("...").

Good to know: Swift Testing has no direct match for XCTAssertEqual(_:_:accuracy:). To compare numbers within a margin, Apple points to isApproximatelyEqual from the swift-numerics package.

Stopping after a failure

In XCTest, you could set continueAfterFailure to false to stop a test after its first failure. XCTest does this by throwing an Objective-C exception. Apple warns that the behavior of an exception thrown through Swift code is undefined, and in async code it can end the process abnormally and stop other tests from running.

Swift Testing does not use exceptions. Use #require, which throws a normal Swift error. Other tests keep running either way.

// After
@Test func truck() throws {
  try #require(FoodTruck.shared.isLicensed)
  ...
}

Testing asynchronous code

XCTest uses expectations that you fulfill and then wait for. Apple's advice is to use Swift concurrency wherever possible. You can await an async function, or wrap a completion-handler function in a continuation.

For events that arrive later and are hard to convert, Swift Testing has confirmations. A confirmation does not block or suspend the test while it waits. Instead, the event must be confirmed before the confirmation() call returns, or an issue is recorded.

// After
@Test func truckEvents() async {
  await confirmation("...") { soldFood in
    FoodTruck.shared.eventHandler = { event in
      if case .soldFood = event { soldFood() }
    }
    await Customer().buy(.soup)
  }
}

By default, a confirmation must happen exactly once, like an XCTest expectation. To allow more, pass an expectedCount range with a lower bound, such as 10.... The lower bound is required, because otherwise the library cannot tell whether zero confirmations is a problem.

Skipping tests

In XCTest you threw XCTSkip or called XCTSkipIf and XCTSkipUnless. In Swift Testing, you add traits to a suite or test before it runs:

// After
@Suite(.disabled(if: CashRegister.isEmpty))
struct FoodTruckTests {
  @Test(.enabled(if: FoodTruck.sells(.arepas)))
  func arepasAreTasty() { ... }
}

If a test is already running and you decide it should end early without failing, use Test.cancel(...) instead of XCTSkip. With interoperability, it can also end XCTest tests, so a shared helper can serve both.

Known issues

When a test has a known problem, XCTest uses XCTExpectFailure. Swift Testing uses withKnownIssue:

// After
@Test func grillWorks() async {
  withKnownIssue("Grill is out of fuel") {
    try FoodTruck.shared.grill.start()
  }
}
  • For a flaky problem, pass isIntermittent: true instead of using a non-strict option.
  • To turn matching on only sometimes, or to match only certain issues, use the when and matching closures.
  • The XCTest version without a closure, which affects the rest of the test, has no direct match. To mark a whole test, wrap its body in withKnownIssue.
  • With interoperability, withKnownIssue can also match XCTest failures.

Running tests one at a time

Swift Testing runs tests in a suite in parallel by default. XCTest runs them one by one. If your tests share state, such as global variables, parallel runs can give unreliable results. Mark the suite with .serialized to run its tests serially.

@Suite(.serialized)
class RefrigeratorTests {
  @Test func lightComesOn() throws { ... }
  @Test func lightGoesOut() throws { ... }
}

Attachments

XCTest uses XCTAttachment to save extra data that helps when a test fails. Swift Testing has an Attachment type. A value must conform to Attachable. If a type already conforms to Encodable or NSSecureCoding, importing Foundation gives it a default implementation. Then you can call Attachment.record(value).

What It Means for Developers

This guide is mostly for people who write tests in Swift for Apple platforms and beyond.

What It Means for Software Developers

  • You do not need a big-bang rewrite. Mix XCTest and Swift Testing in one file and move over test by test.
  • Turn on interoperability first, so shared helpers stop hiding failures.
  • Prefer structs for suites and use init() for setup, which fits Swift's concurrency checks.
  • Check suites for shared state, since tests now run in parallel unless you add .serialized.
  • Read Apple's docs on defining tests and organizing tests with suites, and compare notes with the older XCTest documentation.
  • For testing the whole Mac app interface, see our story on E2E's macOS desktop engine.

What It Means for DevOps Engineers

  • Check the toolchain version and swift-tools-version in your packages, because they set the default interoperability mode.
  • Use the SWIFT_TESTING environment variable in CI if you want a specific mode across all builds.
  • Expect new warnings in limited mode and failures in complete mode for old XCTest assertions called from Swift Testing tests.
  • Watch for flaky results from parallel runs and plan to serialize suites that share state.

Bottom line

Apple's guide gives a clear path from XCTest to Swift Testing. Change the import, turn classes into suites, mark tests with @Test, and swap assertions for #expect and #require.

Thanks to interoperability, you can do this slowly. Start with shared helpers, move simple tests first, and handle parallel runs and async tests with care.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author