DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • A Developer’s Guide to Multithreading and Swift Concurrency
  • Setup Cypress Tests in Azure DevOps Pipeline
  • Migrating From the OpenAI API to vLLM: Configure It Right
  • Detecting Requirement Drift in Automated Test Suites Through Content Hashing and Impact Analysis

Trending

  • Java: A Time-Tested Programming Language Still Going Strong
  • Building a Windows App for a Resilient SSH SOCKS Proxy and Selective Browser Routing
  • Java Virtual Threads Under Load: Three Production Limits
  • Building a Feature Store With Neo4j and Feast

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Testing Async Code in Swift: Stop Using Task.yield() in Your Tests

Testing Async Code in Swift: Stop Using Task.yield() in Your Tests

Make Swift concurrency tests deterministic by injecting an ITaskFactory and waiting for created tasks to finish with waitUntilIdle().

By 
Nikita Vasilev
·
Nov. 23, 26 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
95 Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Testing async code in Swift often turns into a lottery: tests pass locally, fail on CI, and people try to fix them with Task.yield() or Task.sleep(). Eventually the team gets used to re-running flaky builds and stops trusting the pipeline.

The problem is usually a race between the test and a task that the object under test creates on its own. Task.yield() can make the test pass, but it doesn’t establish any ordering between the two. To make the test deterministic, it needs control over the tasks it creates indirectly.

If you can make a method async, do it. This article is about a different situation: integrating async code into synchronous entry points you can’t control, such as UIKit and SwiftUI lifecycle methods.

Why the Test Fails

Take a ProfileViewModel whose load() starts a Task, fetches the user name through a service, and stores it in a property:

Swift
 
@MainActor
final class ProfileViewModel {
    private(set) var userName = ""
    private let userService: IUserService

    init(userService: IUserService) {
        self.userService = userService
    }

    func load() {
        Task {
            userName = await userService.fetchUserName()
        }
    }
}
Swift
 
@MainActor
func testLoad() {
    // when
    viewModel.load()

    // then
    XCTAssertEqual(viewModel.userName, "Alice") // failed
}


The test fails because load() returns right after creating the Task, so the assertion runs before the task body does. In this case it’s not even a race: ProfileViewModel is isolated to the main actor, and a synchronous test holds the main thread until it returns. The task can only run after the assertion has already executed.

Making the test async turns this into a real race between the task and the assertion, and the outcome depends on scheduling.

Why Task.yield() Doesn’t Fix It

A common suggestion is to yield to the created task before asserting:

Swift
 
// Dangerous, flaky test
@MainActor
func testLoad() async {
    // when
    viewModel.load()
    await Task.yield() // give way to the created task

    // then
    XCTAssertEqual(viewModel.userName, "Alice")
}


or, with Swift testing:

Swift
 
@Test @MainActor
func load() async {
    // when
    viewModel.load()
    await Task.yield() // give way to the created task

    // then
    #expect(viewModel.userName == "Alice")
}


Locally, such a test often passes, which is what makes it dangerous.

  • Task.yield() gives other tasks a chance to run: “if there are other tasks in the pool, you may hand control to them.” It doesn’t guarantee that the task you care about will get a thread, let alone run to completion.
  • The task has suspension points. Inside the Task there’s await userService.fetchUserName(). A single yield may not be enough for the task to get past this await and reach the write to userName. The outcome depends on how the scheduler happens to distribute work at that moment.
  • The result depends on load. Run such a test on a busy CI server, or repeat it 100 times in a row, and a few runs will fail at random. A flaky test is worse than a consistently red one, because a red test at least points at a real problem.
  • Execution order is not guaranteed. Apple’s documentation doesn’t promise any specific order of execution after Task.yield(), so an assertion built on it relies on a scheduler implementation detail.

Controlling Task Creation With ITaskFactory

Instead of calling Task { ... } directly, we create tasks through an injected factory. The test implementation keeps track of those tasks and lets the test wait for them explicitly.

Step 1: An Abstraction Over Task Creation

Production code gets a task factory protocol:

Swift
 
protocol ITaskFactory {
    @discardableResult
    func task<Success: Sendable>(
        priority: TaskPriority?,
        @_inheritActorContext operation: sending @escaping @isolated(any) () async -> Success
    ) -> Task<Success, Never>
}


Protocol requirements can’t have default values, so we add a default priority through an extension:

Swift
 
extension ITaskFactory {
    @discardableResult
    func task<Success: Sendable>(
        @_inheritActorContext operation: sending @escaping @isolated(any) () async -> Success
    ) -> Task<Success, Never> {
        task(priority: nil, operation: operation)
    }
}


The production implementation is trivial: it just creates a task.

Swift
 
struct TaskFactory: ITaskFactory {
    @discardableResult
    func task<Success: Sendable>(
        priority: TaskPriority?,
        @_inheritActorContext operation: sending @escaping @isolated(any) () async -> Success
    ) -> Task<Success, Never> {
        Task(priority: priority, operation: operation)
    }
}


Production behavior stays the same; the factory just gives tests a way to observe the tasks being created.

Step 2: A Test Factory That Remembers Every Task

The test implementation keeps track of the tasks it creates and provides waitUntilIdle() to wait for them.

Task has generic success and failure types, so we can’t put arbitrary tasks directly into one array. ITask gives us a common interface for waiting on them.

Swift
 
/// A protocol representing a task that can be awaited until its execution completes.
protocol ITask {
  /// Waits for the `Task` to complete by retrieving its result.
  func wait() async
}

// MARK: - Task + ITask

/// Extends the `Task` type to conform to the `ITask` protocol.
extension Task: ITask {
  func wait() async {
    _ = await result
  }
}
Swift
 
public final class TestTaskFactory: @unchecked Sendable {
  // MARK: Properties

  private let lock = NSLock()
  private var tasks: [ITask] = []

  // MARK: Initialization

  public init() {}

  // MARK: Public

  /// Waits until all tasks in the queue have completed execution.
  public func waitUntilIdle() async {
    while let task = popTask() {
      await task.wait()
    }
  }

  // MARK: Private

  private func addTask(_ task: ITask) {
    lock.lock()
    defer { lock.unlock() }
    tasks.append(task)
  }

  private func popTask() -> ITask? {
    lock.lock()
    defer { lock.unlock() }
    return tasks.popLast()
  }
}

// MARK: ITaskFactory

extension TestTaskFactory: ITaskFactory {
  public func task<Success: Sendable>(
    priority: TaskPriority?,
    @_inheritActorContext operation: sending @escaping @isolated(any) () async -> Success
  ) -> Task<Success, Never> {
    let task = Task(priority: priority, operation: operation)
    addTask(task)
    return task
  }
}


The while loop is important here. A task can create another task through the same factory, so waiting for the initial batch isn’t enough. We keep draining the queue until there are no tasks left.

waitUntilIdle() waits for tasks to finish, so it will hang if one of them never completes (an endless for await loop, a continuation that is never resumed, a mock that never calls back). In such cases, cancel the pending tasks (for example, with a cancelAll() helper in your own test factory) or add a timeout. Also remember that it only sees tasks created through the factory.

Step 3: Injecting the Factory into ProfileViewModel

Swift
 
@MainActor
final class ProfileViewModel {
    private(set) var userName = ""
    private let userService: IUserService
    private let taskFactory: ITaskFactory

    init(userService: IUserService, taskFactory: ITaskFactory) {
        self.userService = userService
        self.taskFactory = taskFactory
    }

    func load() {
        taskFactory.task {
            self.userName = await self.userService.fetchUserName()
        }
    }
}


Step 4: A Stable Test

Swift
 
@MainActor
func testLoad() async {
    // given
    let taskFactory = TestTaskFactory()
    let viewModel = ProfileViewModel(
        userService: userServiceMock,
        taskFactory: taskFactory
    )

    // when
    viewModel.load()
    await taskFactory.waitUntilIdle()

    // then
    XCTAssertEqual(viewModel.userName, "Alice")
}


waitUntilIdle() returns only after every task created through the factory has finished, so the assertion no longer depends on scheduling.

Ready-Made Implementation

You don’t have to write all of this from scratch in every project. An ITaskFactory implementation, along with test doubles for tasks and DispatchQueues, is available in the open source library space-code/concurrency. It’s designed as a set of concurrency primitives that make your code more testable. The library is installed via Swift Package Manager.

What About XCTestExpectation and confirmation?

XCTest has XCTestExpectation and Swift testing has confirmation, so why not use them? They verify that an event happened, while here we need to know that the work has finished. A test using confirmation:

Swift
 
@Test @MainActor
func load() async {
    await confirmation { fetched in
        userServiceMock.onFetchUserName = { fetched() }
        viewModel.load()
    }
    #expect(viewModel.userName == "Alice")
}


confirmation requires the confirmation to happen before the closure body returns. But load() returns immediately, and fetchUserName() is called later inside the task. The confirmation arrives too late, and the test fails.

With XCTestExpectation, the test can still race:

Swift
 
@MainActor
func testLoad() async {
    // given
    let called = expectation(description: "fetchUserName called")
    userServiceMock.onFetchUserName = { called.fulfill() }

    // when
    viewModel.load()

    // then
    await fulfillment(of: [called], timeout: 1)
    XCTAssertEqual(viewModel.userName, "Alice") // still a race
}


The expectation is fulfilled when fetchUserName() is called, which is before the task writes the result to userName. The wait is over, but the work isn’t, so the assertion races with the task again, and you also have to pick a timeout.

Both tools are still the right choice for callbacks, delegates, NotificationCenter, Combine publishers, and tasks created by code you don’t control. For a Task you create yourself, waitUntilIdle() is the more direct tool.

Edge Cases

Task Cancellation

The factory returns a Task, so you can store it and call cancel(). The test factory lets you verify this scenario too: create a task, cancel it, call waitUntilIdle(), and make sure there were no side effects. This works if the operation itself responds to cancellation correctly, for example by checking Task.isCancelled or using cancellable awaits.

Don’t Overuse the Factory

The factory is for places where you start a fire-and-forget task from a synchronous context, such as load() in a view model. If a method can be async itself, it’s better to make it so and simply call it with await in the test. Then you don’t need the factory at all.

The approach also has a cost: every Task in production code has to go through the factory, which adds a dependency to initializers and requires discipline from the whole team. It pays off for code with real async logic that you want to cover with tests, and is overkill for trivial one-liners.

Alternatives

  • Make the API async. If load() is async, the test is just await viewModel.load(). This is the simplest option, but it moves the responsibility for creating the Task to the caller.
  • XCTestExpectation. Suitable for external events, but it needs a timeout.
  • Explicit task factory. It requires discipline (no direct Task { } calls), but gives full control over completion without depending on runtime details.

Conclusion

Task.yield() and sleep only hide the race between the test and the task. To remove it, create tasks through an ITaskFactory and wait for them in the test with waitUntilIdle().

The trade-off is an extra dependency in the initializer. For fire-and-forget tasks started from synchronous APIs, it gives the test control over task completion without relying on scheduler timing.

Swift (programming language) Task (computing) Testing

Published at DZone with permission of Nikita Vasilev. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • A Developer’s Guide to Multithreading and Swift Concurrency
  • Setup Cypress Tests in Azure DevOps Pipeline
  • Migrating From the OpenAI API to vLLM: Configure It Right
  • Detecting Requirement Drift in Automated Test Suites Through Content Hashing and Impact Analysis

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook