When it comes to TDD UIStoryboardSegues there are several things you need to consider. A segue can be manually triggered, when used within a UIViewController, or connected as action to a e.g. UIBarButtonItem/UIButton.
The first question you’d ask is:“Is the segue connected?“
Unfortunately for manually triggered segues there is no way to access, so we are going to trigger the segue and see if it throws an exception (not connected) or not.As an example for the Target-Action design pattern here is how to test an UIBarButtonItem.
Does it work as expected?
As this is mainly relevant for manually triggered segues where you decide conditionally which segue you trigger, we have to intercept the prepareForSegue:sender method during test.
The approach here is a two step one. First we extend our view controller class by a category where we implement our own test_prepareForSegue:sender method. During the test we exchange both methods using the method swizzling feature of the objective-c runtime. Here is our helper method for doing so.
Don’t forget to #import <objc/runtime.h>As you can see we store the sender and the segue for later use using the runtime feature objc_setAssociatedObject which allows variable storage within a category.
So now everything is prepare and we can start.
We first exchange the implementation with our own on
Trigger the method which decides about which segue needs to be triggered
Check if the correct segue is triggered by looking for the correct destionation view controller and if the sender is our system under test (sut)
My setup includes the iPad case handling as well as when your first view controller is a UINavigationController.
Hope you find the pattern useful – happy TDD-ing 🙂