3

I want to mock an object with the following message declaration:

- (void)createWithCompletion:(void (^)(FuseResult *result, NSError *err)) completion;

Is it possible to mock the block call this message has to handle?

I read the ArgumentCaptorTest which has block but I wasn't sure if it's relevant.

huggie
  • 17,587
  • 27
  • 82
  • 139

1 Answers1

6

Scroll down to the bottom of https://github.com/jonreid/OCMockito and you'll see "Capturing arguments for further assertions". The second example shows how to use MKTArgumentCaptor to capture a block argument, then call it.

Here's an example:

MKTArgumentCaptor *argument = [[MKTArgumentCaptor alloc] init];
[verify(mockObject) createWithCompletion:[argument capture]];
void (^completion)(FuseResult *result, NSError *err) = [argument value];
completion(someResult, someErr);

This doesn't make mockObject call the block in any way. Instead, it captures the block passed to mockObject. The final step is to call the captured block with whatever arguments you want for your test.

Jon Reid
  • 20,545
  • 2
  • 64
  • 95
  • I am kind of confused to what exactly that does. I want to specify *a priori* the behavior how the mock would call with a particular set of argument to this block when the message is being sent to the mock. (I want something akin to this `given([obj createWithCompletion:]) willReturn`). Is that what's possible there? – huggie Dec 05 '13 at 02:05
  • No. With the argument captor, a test grabs the block that was passed in, then calls whatever it wants to on the block. So basically, the "act" portion of the test has two steps. – Jon Reid Dec 05 '13 at 16:49
  • Great, finding it pretty useful after trying it out. – huggie Dec 07 '13 at 15:49
  • Is it possible to verify if this calls gets called at all? Right now if it doesn't get called MKTCapturingMatcher would throw NSException. Am I suppose to catch this? – huggie Dec 08 '13 at 01:17
  • You shouldn't have to deal with exceptions. Please file an issue at https://github.com/jonreid/OCMockito – Jon Reid Dec 08 '13 at 01:50
  • I submitted at https://github.com/jonreid/OCMockito/issues/51. Thanks for the great framework. – huggie Dec 09 '13 at 02:50
  • @JonReid - Is there anything similar to the Kiwi's 'stub and do': `[[myObj stub] andDo:^(NSInvocation *invocation) { ... }];`. This was handy in Kiwi since you could replace a given method with your own implementation. – Robert Apr 24 '14 at 11:43
  • @Robert There is now.`willDo:` – Jon Reid Jan 22 '16 at 16:20