Daniel Doubrovkine bio photo

Daniel Doubrovkine

aka dB., @awscloud, former CTO @artsy, +@vestris, NYC

Email Twitter LinkedIn Github Strava
Creative Commons License

Let’s mock a UIAlertView with OCMock. Here’s a simple alert:

UIAlertView *alert = [[UIAlertView alloc]
   initWithTitle:@"Title"
   message:@"Please press a button."
   delegate:...
   cancelButtonTitle:@"Cancel"
   otherButtonTitles:@"OK", nil];

[alert show];

And a test that ensures that the alert has been displayed.

id mockAlertView = [OCMockObject mockForClass:[UIAlertView class]];
[[[mockAlertView stub] andReturn:mockAlertView] alloc];
(void)[[[mockAlertView expect] andReturn:mockAlertView]
                          initWithTitle:@"Title"
                                message:@"Please press a button."
                               delegate:OCMOCK_ANY
                      cancelButtonTitle:OCMOCK_ANY
                      otherButtonTitles:OCMOCK_ANY, nil];
[[mockAlertView expect] show];

// make the alert appear here

[mockAlertView verify];
[mockAlertView stopMocking];

The only interesting thing here is that you need to stopMocking the class or other tests will still have the mock enabled and will expect show to be called, producing weird and seemingly unrelated errors.

Related to this – if you’re going to be performing actions based on UIAlertView button presses, I highly recommend UIAlertView+Blocks, which lets you write the callback inline with the view. I haven’t figured out how to test that, you can help me on StackOverflow.