# Mixing async/await code with waitForExpectations in tests causes hang

**URL:** <https://forums.swift.org/t/mixing-async-await-code-with-waitforexpectations-in-tests-causes-hang/62773>\
**Category:** Using Swift\
**Tags:** xctest, asyncawait\
**Created:** [January 24, 2023, 6:01pm UTC](https://forums.swift.org/t/mixing-async-await-code-with-waitforexpectations-in-tests-causes-hang/62773 "2023-01-24T18:01:50Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tunous](https://avatars.discourse-cdn.com/v4/letter/t/f07891/32.png) [@Tunous](https://forums.swift.org/u/Tunous)\
**Post date:** [January 24, 2023, 6:01pm UTC](https://forums.swift.org/t/mixing-async-await-code-with-waitforexpectations-in-tests-causes-hang/62773/1 "2023-01-24T18:01:50Z")

</div>

I've encountered a problem with awaiting expectations in `XCTestCase` when testing async code. I want to test code that is supposed to execute operations in background and notify me about the result.

The problem is that once background operation finishes nothing happens. Instead my expectation times out after the specified time. Below is a simplified model and test case that simulates my code. Running it displays only "before doSomethingAsync" and "in doSomethingAsync" messages in console. It looks to me like execution is not returning to main actor while `waitForExpectations` is running.

```swift
@MainActor
final class ViewModel: ObservableObject {
    let didRun: () -> Void

    init(didRun: @escaping () -> Void) {
        self.didRun = didRun
    }

    func doSomething() {
        Task {
            print("before doSomethingAsync")
            await doSomethingAsync()
            print("after doSomethingAsync")
            didRun()
        }
    }

    nonisolated func doSomethingAsync() async {
        print("in doSomethingAsync")
    }
}

final class AsyncTestTests: XCTestCase {
    func testDoSomething() async throws {
        let exp = expectation(description: "task finished")
        let viewModel = await ViewModel(didRun: {
            exp.fulfill()
        })

        await viewModel.doSomething()

        await waitForExpectations(timeout: 5)
    }
}

```

Is there anything that I'm doing incorrectly here or perhaps is it an issue with `waitForExpectations` function?

I'm using Xcode 14.2 with iOS 16.2 simulator.

---

<div class="post-metadata">

**Author:** ![Tunous](https://avatars.discourse-cdn.com/v4/letter/t/f07891/32.png) [@Tunous](https://forums.swift.org/u/Tunous)\
**Post date:** [January 24, 2023, 7:02pm UTC](https://forums.swift.org/t/mixing-async-await-code-with-waitforexpectations-in-tests-causes-hang/62773/2 "2023-01-24T19:02:39Z")

</div>

I noticed that there is a note in [documentation](https://developer.apple.com/documentation/xctest/xctestcase/1500748-waitforexpectations) that says “Clients should not manipulate the run loop while using this API.”. Perhaps this means that something like I’m trying to do is not supported. If that is the case is there an alternative approach?

---

<div class="post-metadata">

**Author:** ![Max\_Desiatov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/max_desiatov/32/20654_2.png) [@Max\_Desiatov](https://forums.swift.org/u/Max_Desiatov)\
**Post date:** [January 24, 2023, 7:28pm UTC](https://forums.swift.org/t/mixing-async-await-code-with-waitforexpectations-in-tests-causes-hang/62773/3 "2023-01-24T19:28:45Z")

</div>

Would something like this work?

```swift
final class AsyncTestTests: XCTestCase {
    func testDoSomething() async throws {
        var didRun = false
        let viewModel = await ViewModel(didRun: {
            didRun = true
        })

        await viewModel.doSomething()

        XCTAssertTrue(didRun)
    }
}

```

---

<div class="post-metadata">

**Author:** ![Tunous](https://avatars.discourse-cdn.com/v4/letter/t/f07891/32.png) [@Tunous](https://forums.swift.org/u/Tunous)\
**Post date:** [January 24, 2023, 8:42pm UTC](https://forums.swift.org/t/mixing-async-await-code-with-waitforexpectations-in-tests-causes-hang/62773/4 "2023-01-24T20:42:02Z")

</div>

Unfortunately that won’t work. `doSomething` launches a Task that won’t complete until later. There is an await in test code only because it runs outside of MainActor. I could annotate whole test with @MainActor like below but that won’t resolve the issue.

```swift
final class AsyncTestTests: XCTestCase {
    @MainActor
    func testDoSomething() async throws {
        let exp = expectation(description: "task finished")
        let viewModel = ViewModel(didRun: {
            exp.fulfill()
        })

        viewModel.doSomething()

        waitForExpectations(timeout: 5)
    }
}

```

---

<div class="post-metadata">

**Author:** ![Tunous](https://avatars.discourse-cdn.com/v4/letter/t/f07891/32.png) [@Tunous](https://forums.swift.org/u/Tunous)\
**Post date:** [February 17, 2023, 7:34am UTC](https://forums.swift.org/t/mixing-async-await-code-with-waitforexpectations-in-tests-causes-hang/62773/5 "2023-02-17T07:34:56Z")

</div>

Per [Xcode 14.3 Beta release notes](https://developer.apple.com/documentation/xcode-release-notes/xcode-14_3-release-notes) Apple confirmed that it was an issue in these functions and provided replacement.

> Fixed: `XCTestCase.wait(for:timeout:enforceOrder:)` and related methods are now marked unavailable in concurrent Swift functions because they can cause a test to deadlock. Instead, you can use the new concurrency-safe `XCTestCase.fulfillment(of:timeout:enforceOrder:)` method. (91453026)

> **[fulfillment(of:timeout:enforceOrder:) | Apple Developer Documentation](https://developer.apple.com/documentation/xctest/xctestcase/4109476-fulfillment)**
>
> Waits on a group of expectations for up to the specified timeout, optionally enforcing their order of fulfillment.

---

<div class="post-metadata">

**Author:** ![kabiroberai](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/kabiroberai/32/28072_2.png) [@kabiroberai](https://forums.swift.org/u/kabiroberai)\
**Post date:** [February 17, 2023, 9:50am UTC](https://forums.swift.org/t/mixing-async-await-code-with-waitforexpectations-in-tests-causes-hang/62773/6 "2023-02-17T09:50:17Z")

</div>

If you’re still curious about the root cause, I think the issue with `waitForExpectations` in async code is that calling it blocks the main thread/queue. Since the async tasks need to run on the main queue too, they wait for the queue to clear up, but the queue never clears up because the `XCTestExpectation` blocking it is waiting for the async tasks — creating a deadlock.

In general you should avoid blocking any execution context that’s running async code (whether that’s the main thread or a global async executor) because that violates the forward progress invariant. There’s a great video on this from WWDC 2021: see [Swift concurrency: Behind the scenes - WWDC21 - Videos - Apple Developer](https://developer.apple.com/videos/play/wwdc2021/10254/).

---

<div class="post-metadata">

**Author:** ![vigdora](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/vigdora/32/34512_2.png) [@vigdora](https://forums.swift.org/u/vigdora)\
**Post date:** [September 14, 2023, 3:21pm UTC](https://forums.swift.org/t/mixing-async-await-code-with-waitforexpectations-in-tests-causes-hang/62773/7 "2023-09-14T15:21:30Z")

</div>

@Tunous  
Did using fulfillment api helped you here eventually?

---

<div class="post-metadata">

**Author:** ![Tunous](https://avatars.discourse-cdn.com/v4/letter/t/f07891/32.png) [@Tunous](https://forums.swift.org/u/Tunous)\
**Post date:** [September 15, 2023, 9:53am UTC](https://forums.swift.org/t/mixing-async-await-code-with-waitforexpectations-in-tests-causes-hang/62773/8 "2023-09-15T09:53:37Z")

</div>

Yes the issue doesn't happen when using fulfillment api.
