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]
   message:@"Please press a button."
   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]
                                message:@"Please press a button."
                      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.