5

Is there a way to stub method, that takes block as it's parameter? For example mehod:

- (void)reverseGeocodeLocation:(CLLocation *)location completionHandler:(CLGeocodeCompletionHandler)completionHandler;
kraag22
  • 3,340
  • 3
  • 29
  • 37

1 Answers1

6

Yes. The easiest way would be to accept anything:

id mockGeocoder = [OCMockObject mockForClass:[CLGeocoder class]];
[[mockGeocoder stub] reverseGeocodeLocation:[OCMOCK_ANY] completionHandler:[OCMOCK_ANY]];

It gets a bit trickier if you want to verify a particular block is passed in. One option is to make your completion handler a property of your class, initialize it when you initialize your class, and have the test match it directly:

// in your class
@property(copy)CLGeocodeCompletionHandler completionHandler;

// in your class's init method
self.completionHandler = ^(NSArray *placemark, NSError *error) {
    //
}

// using the completion handler
[geocoder reverseGeocodeLocation:location completionHandler:self.completionHandler];

// the test
id mockGeocoder = [OCMockObject mockForClass:[CLGeocoder class]];
[[mockGeocoder stub] reverseGeocodeLocation:[OCMOCK_ANY] completionHandler:yourClass.completionHandler];
Christopher Pickslay
  • 17,523
  • 6
  • 79
  • 92
  • 1
    This will ensure that the stub method is called, but won't actually do anything with the block passed in, correct? Is there any way to do anything with the block parameter, specifically run it? I have a very similar scenario, but I want my mock object to run the block passed in to complete the test. – Mike May 13 '13 at 19:51
  • 1
    What's the version 3 answer? – Bernard Jun 10 '16 at 17:02