'XCTest: Wait for async call to finish in synchronous function
I have a synchronous function that calls an asynchronous sub function. Now I want to test that the synchronous function sets a property. I've seen many examples of tests using expectations, but since only the sub function is async, I can't set fulfill.
What I would like to do instead is to just do an XCTAssertEqual checking the property to equal a certain value within a given timeout period.
How can this be done?
Here's a sketch:
class TestSubject {
var noOfCalls = 0
func funcToTest() {
Task.init {
await doSomething()
await doSomething()
}
}
func doSomething() async {
...
noOfCalls++
}
}
The test:
func testTestSubject() async {
var subject = TestSubject()
subject.funcToTest()
// this obviously doesn't work because of the async call
XCTAssertEqual(subject.noOfCalls, 2)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|