samedi 10 septembre 2016

Unit test property has changed after dispatch_async using XCTest

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:

  1. Wrap dispatch_async in a helper so that the dispatch_async can 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()
        }
    }
    
    
  2. Wait for the next run loop

Aucun commentaire:

Enregistrer un commentaire