Handle MainThread execution in Unit Test

Viewed 1565

I have a function that is run on the background and when complete it updates UI in the main thread. I've noticed the unit test fails when the code reaches the call to the main thread. How do I rectify this ?

For e.g NB: The long depicts the pseudo logic in the project and not the exact code

In main code :

func getResponse(identifier : String, completion :(success :Bool)->){
   // uses identifier to request data via api and on completion:
   completion(status: true)
}

testObject.getResponse(wantedValue){(success) in
    if status == true {
        dispatch_async(dispatch_get_main_queue()){
           self.presentViewController(alertController, animated: true, completion: nil)

           }
     } 
}

And in the Unit test

func testGetResponse(){
     var testObject = TestObject()
     var expectation = self.self.expectationWithDescription("Response recieved")

     testObject.getResponse(wantedValue){(success) in
          expectation.fulfill()
     } 

     self.waitForExpectationsWithTimeout(10) { (error) in
        XCTAssertTrue(testViewController.presentedViewController as? CustomViewController)
     }
}

It seems the is a potential deadlock but I am not certain as to how to work around it.

1 Answers
Related