Search code examples
swiftxcodeunit-testingasynchronousxctest

Why this test case hangs when run on a simulator?


Consider this simple test case

func test_Example() async {
    let exp = expectation(description: "It's the expectation")
        
    Task {
        print("Task says: Hello!")
        exp.fulfill()
    }
        
    wait(for: [exp], timeout: 600)
}

When I run this on an actual device, the test passes. However, when I run it on a simulator, it hangs and never completes.

Removing the async keyword from the function declaration solves the issue and the test passes on a simulator as well.

My actual use case / tests require the test to be async, so removing it is not really an option.


Solution

  • Solution: Change wait(for:) to await waitForExpectations(timeout:)

    I don't know why it works, but probably it has something to do with the limited amount of threads available in a simulator.

    waitForExpectations(timeout:) is marked with @MainActor and wait(for:) is not.