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.

1 Answer 1

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.

8
  • 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 5, 2013 at 2: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 5, 2013 at 16:49
  • Great, finding it pretty useful after trying it out.
    – huggie
    Dec 7, 2013 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 8, 2013 at 1:17
  • You shouldn't have to deal with exceptions. Please file an issue at github.com/jonreid/OCMockito
    – Jon Reid
    Dec 8, 2013 at 1:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.