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
Answers 1
The waitForExpectationsWithTimeout is also the fallback method for the case that your async function is not called or has not been finished properly (and so did not call the fulfill() method).
Try to check the error object.
I would recommend to do the validation before doing the fullfill() call.
See the following example code for Swift 3 how to use the 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)") } } }
0 comments:
Post a Comment