Reputation: 355
I'm trying to test some asynchronous code using Unit Tests in Xcode, but I'm getting a blocked main thread.
The problem is that some of the code being tested expects to receive a callback from an iOS class (AVFoundation). However, it seems the AVFoundation class will only callback on the Main thread.
The problem is that if I'm doing an async unit test, then the test actually blocks the main thread while it's waiting, so the callback can never be sent.
I'm pretty sure this is the problem. Is there any way to run the tests from another thread or have an XCTWaiter
that doesn't block the main thread?
Edit: After looking a bit at the docs, it seems like the best way to do this would be to run the entire test case on a background thread. However, in my current project the testing is all set up automatically. I wonder if anyone knows how to setup a test case / run manually. That way I could run it on another thread.
Upvotes: 9
Views: 4518
Reputation: 3614
Considering @BetterLateThanNever's answer. Here is the code snippet how I test my code using callback in main-thread.
func test() {
let expectation = XCTestExpectation(description: "Test")
DispatchQueue.global(qos: .default).async {
...
...
let myObj = MyObj()
myObj.runSomethingMayWaitForMainThread()
...
...
XCTAssert(myObj.result)
expectation.fulfill()
}
wait(for: [expectation], timeout: 50.0)
}
Upvotes: 7
Reputation: 71
This is more than a year late so probably not relevant anymore, but I encountered this as realized that XCTestExpectation fixes the issue (not sure if that was available when you posted the question).
Waiting for expectations does not block the main thread and allows other work dispatched to the main thread asynchronously to proceed as expected. Hope this helps
Upvotes: 7