Testing callback with delegate methods in Swift

Apple has now made it possible to test callback methods in unit tests for swift.

It works great on callback methods directly, but also works if you have delegates reacting to the callback in another class

The trick is to use the XCTestExpectation class.

In the function where you call the callback method, you must instantiate an expectation object like this:

//Declare the expectation object
var expectation: XCTestExpectation!
func doSomeTesting(){
  expectation = expectationWithDescription("Waiting for delegates”)
  …… do other stuff call the callback
  //start the waiting
  waitForExpectationsWithTimeout(5) { (error) in  //5 seconds waiting time
     println( error )
  }
  //assert something
  XCTAssert(true, "Pass")

}

func theMethodFromDelegateProtocol( someThing:AnyObject){
//Do some other stuff with the someThing object
//and fulfill the expectation to avoid errors
   expectation.fulfill()
}

That is relatively, actually very, easy to set up and use. Just remember to set the waiting time realisticly (low or high)

Posted in Swift Programming