Test Delegate Methods

Delegate methods are the classic way for Cocoa Touch to call back to our code. Thankfully, we don’t have to try to coax this to happen in test code. For unit tests, it doesn’t matter what calls a delegate method. We only have to mimic the arguments and call the method directly. So what Cocoa Touch would call, the test calls.

Let’s consider how to test the first delegate method, textField(_:shouldChangeCharactersIn:replacementString:). To test with a naive approach, we do two things:

  • First, test that the delegate of the text field is the view controller.
  • Second, call the delegate method directly on the view controller.

The problem with this approach is that it locks down who gets to be the delegate. Programmers earlier ...

Get iOS Unit Testing by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.