Testing async code

Testing Mid-level Swift 5.5+ iOS 17+ Reviewed By Alok Singh

Pick the fix

How should you test func load() async throws on a @MainActor view model?

Options
Hint 1 of 1

Tests can be async too.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A A @MainActor async test that calls try await viewModel.load() and then asserts

Correct. It awaits the real work, with no sleeps.

Why not the others?
  • B Call load in a Task, sleep 2 seconds, then assert. Slow, and flaky under load.
  • C Use DispatchSemaphore to block until it finishes. Blocking can deadlock with main-actor work.
  • D Only test the synchronous parts. The async path is where bugs hide.

30-second answer

Mark the test async (and throws) and await the code directly; XCTest and Swift Testing both support it. For callback or delegate APIs, use XCTestExpectation with await fulfillment(of:timeout:), or confirmation in Swift Testing. Test main-actor types from @MainActor tests, and control time and dependencies instead of sleeping.

Practise saying it · 30 s. No recording, just a timer

Explain how you test async code.

Say your answer out loud, then check which of these points you covered:

  • async test methods
  • Expectations for callbacks
  • No sleeps

Deep dive

Use wait(for:) only in synchronous tests; in async tests use await fulfillment(of:).

Inject services that return immediately or throw on demand.

Assert on cancellation paths too.

Keep timeouts generous for CI, but never rely on them for correctness.

Common mistakes

  • Sleeping to wait for work.
  • Using wait(for:) inside an async test, which can deadlock.

Senior take & follow-ups

Seniors await work directly and reach for expectations only for callback APIs.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you test a delegate callback?

    Show hint

    An expectation fulfilled in the delegate method.

  2. How do you test a @MainActor view model?

    Show hint

    Mark the test or suite @MainActor.

Suggest a fix if something here is wrong or out of date.