Executing MainThread Handle in Unit Test
I have a function that runs in the background and updates the interface on the main thread when finished. I noticed that the unit test fails when the code reaches a call to the main thread. How do I fix this?
For example NB: long depicts pseudo logic in the project and not exact code
In the 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 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)
}
}
This seems like a potential dead end, but I'm not sure how to get around it.
source to share
waitForExpectationsWithTimeout is also a return method for when your async function is not being called or executed as expected (and therefore did not call execute ()).
Try to check the error object.
I would recommend checking before making the fullfill () call.
See the following sample code for Swift 3 for how to use fullfill and waitForExpectationsWithTimeout.
func testGetResponse(){
var testObject = TestObject()
var validationExpectation = expectation(description: "Response received")
testObject.getResponse(wantedValue){(success) in
// Do your validation
validationExpectation.fulfill()
// Test succeeded
}
waitForExpectationsWithTimeout(60) { (error) in
if let error = error {
// Test failed
XCTFail("Error: \(error.localizedDescription)")
}
}
}
source to share