Sometimes you might want to create a mock instance of
UIApplication to test whether your code calles a certain method correctly - e.g.
openUrl(). In Objective-C this was an easy task with OCMock but in Swift it’s a bit tricky.
Trying the usual Swift mocking approach by creating a subclass of the class you want to mock and overriding the methods you want to test fails for UIApplication since the system only allows one UIApplication instance and crashes if you try to instantiate a subclass of it.
Protocols to the rescue!
We can just create a new protocol and let
UIApplication conform to it:
Now we can use the protocol instead of
In the unit test we now just create another implementation of the
UIApplicationProtocol to verify that it was called correctly: