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, andXCTAssertGreaterThan, 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.
XCTAssertThrowsErrorcan't take anasyncexpression.- 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.
@Testand@Suitedeclare tests explicitly. No naming conventions.#expectand#requirereplace the entireXCTAssertfamily. 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
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.
- Collects every test and its traits.
- Expands parameterized tests into one test case per argument.
- 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
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 |
|
| Performance testing | measure {} |
|
| Objective-C | ||
| Process exit tests | ||
| 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
}
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))
}
}
}
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)
}
}
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))
}
}
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: collectionruns 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 { … }
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)
}
.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
letproperties are never shared between tests. - Actor isolation: Mark a suite with
@MainActorto 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)
}
}
- 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."))
}
expectedCount: 0asserts something never happens. XCTest needsisInvertedand a timeout for that.- From Swift 6.1,
expectedCountalso accepts a range, such as1.... - If your callback API has no "done" point to await (for example, a fire-and-forget
NotificationCenterpost on another queue), wrap it in anAsyncStreamand await it inside the closure. Or keep that test in XCTest, wherefulfillment(of:timeout:)does wait.
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
From Swift 6.1, the type form returns the caught error, so you can inspect it (see thrownErrorCanBeInspected above).
Custom traits: replacing setUp/tearDown with something reusable
A trait that conforms to TestScoping (Swift 6.1+) wraps each test it's applied to. This one gives each test its own temporary directory and always deletes it afterwards:
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() }
}
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)
}
}
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 the trait hands values to the test. It's safe even with parallel tests, because 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
}
In Xcode you can group tests by tag in the Test navigator and include or exclude tags in a test plan. Neither swift test nor xcodebuild has a tag filter flag, so on the command line filter by name (section 9).
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
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
Step 2: pick the first tests to migrate
Good first candidates:
- Pure logic tests: validators, formatters, mappers, reducers. These are mechanical to convert.
- Tests with loops over inputs. They become parameterized tests and get clearer failure reports.
- Async tests that use the
do/catch+XCTFailpattern. These become a single#expect(throws:).
Migrate later, or never:
- Tests built around
XCTestExpectationwith 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))
}
}
(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:
- Replace
import XCTestwithimport Testing, or keep both while the file is mid-migration. - Change
final class FooTests: XCTestCasetostruct FooTests. Add@Suite("…")if you want a display name or traits. - Move
setUp()work intoinit()(it can beasync throws), and turnvar x: T!intolet x: T. - Delete
tearDown()if it only nils out properties. Move real cleanup todeinit(on afinal classsuite) or a scoping trait. - Change
func testFoo()to@Test func foo(). - 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 plainawait
- Turn input loops into
@Test(arguments:). - 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"]),
]
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
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
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.sharedwith a stubbedURLProtocol,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.
(Part 2 — production example, common mistakes, CI/CD and conclusion — continues in the next post.)

