Can OCMock run a block parameter?

Mike picture Mike · May 13, 2013 · Viewed 15.7k times · Source

Assume a method signature such as the following:

- (void)theMethod:(void(^)(BOOL completed))completionBlock;

I would like to mock this method signature to ensure the method is called, and just call the completion block. I see from other posts like this one that I can mock the method call and accept any block, but not run the block. I also know there is a andDo method that I might be able to use, but I can't figure out how to pass a block in and run it.

Any ideas?

Thanks.

Answer

Sven picture Sven · May 13, 2013

You can use [[mock stub] andDo:] like this to pass another block that gets called when your mocked method is called:

void (^proxyBlock)(NSInvocation *) = ^(NSInvocation *invocation) {
     void (^passedBlock)( BOOL );
     [invocation getArgument: &passedBlock atIndex: 2];
};
[[[mock stub] andDo: proxyBlock] theMethod:[OCMArg any]];

The block gets a NSInvocation instance from which you can query all the used arguments. Note that the first argument is at index 2 since you have self and _cmd at the indices 0 and 1.