What is the best way to unit test importantMainThreadStuffHasHappened is set to true after the dispatch_async in the code below?
class ViewController: UIViewController {
var importantMainThreadStuffHasHappened = false
override func viewDidLoad() {
super.viewDidLoad()
dispatch_async(dispatch_get_main_queue()) {
self.importantMainThreadStuffHasHappened = true
}
}
}
This does not work since the dispatch_async code is executed after the XCTAssertTrue in the test.
func testimportantMainThreadStuffHasHappened() {
let viewController = ViewController()
_ = viewController.view
XCTAssertTrue(viewController.importantMainThreadStuffHasHappened)
}
I've heard two suggestions so far, both of which seem pretty outlandish:
-
Wrap
dispatch_asyncin a helper so that thedispatch_asynccan be replaced in a mock like:protocol Dispatcher { func asyncMain(completion: dispatch_block_t) } struct Dispatch: Dispatcher { func asyncMain(completion: dispatch_block_t) { dispatch_async(dispatch_get_main_queue()) { completion() } } } struct MockDispatch: Dispatcher { func asyncMain(completion: dispatch_block_t) { completion() } } -
Wait for the next run loop
Aucun commentaire:
Enregistrer un commentaire