-
-
Save robertmryan/8989dade9c5bef9ac0db75040d65f747 to your computer and use it in GitHub Desktop.
class MyAppTests: XCTestCase { | |
func testIets() { | |
let expectation = self.expectation(description: "doSomething") | |
AsyncClass().doSomething { | |
expectation.fulfill() | |
} | |
wait(for: [expectation], timeout: 5) | |
} | |
} | |
class AsyncClass { | |
func doSomething(completion: @escaping () -> Void) { | |
let group = DispatchGroup() | |
for _ in 0...5 { | |
group.enter() | |
DispatchQueue.global().async { | |
Thread.sleep(forTimeInterval: 1) | |
group.leave() | |
} | |
} | |
group.notify(queue: .main) { | |
completion() | |
} | |
} | |
} |
In the end, I just wanted this:
func testIets() {
var isCalled = false
AsyncClass().doSomething()
var isCalled = true
XCTAssert(isCalled)
}
(ofcourse without the boolean isCalled). If you haven't seen it, I implemented this behavior: https://stackoverflow.com/a/58576029/7715250. As I explained it inside many comments, I want to fill my database with random data. Thats expensive CPU operation, so I want to dispatch it to all available threads, so not only the calling thread. I also want it sync, because I don't want to deal all the time with all the expectations and closures. If there is a better way, I would like to see how :)
@Jasperav - IMHO, it’s not advisable to introduce anti-patterns into one's codebase solely for the sake of testing, when the testing framework already provides a nice, concise mechanism to test these scenarios.
My suggestion is that you do not add blocking/synchronous methods to your code base, and instead use expectations when testing.
It strikes me that the expectation code shown above is just as concise and intuitive as your original code snippet (shown below), and it doesn’t require any changes to your
doSomething
method: