6

is there any way to invoke a block with nil as a given argument, given that the invokeBlockWithArgs: requires the args to be nil-terminated?

example method definition in a mocked object:

- (void)methodWithCompletion:(void(^)(NSString*, NSError* )) completionBlock;

The given mockObject should call:

completionBlock(@"foo", nil);

however, with invokeBlockWithArgs:

OCMStub([mockObj methodWithCompletion:([OCMArg invokeBlockWithArgs:@"foo", nil, nil])]);

Method fails, with too few arguments; obviously with nil being the termination, it doesn't recognize the second parameter to the block should be nil.

cyrix
  • 308
  • 2
  • 7

3 Answers3

9

I haven't tested it but theoretically passing [NSNull null] should work.

Erik Doernenburg
  • 2,933
  • 18
  • 21
  • I believe I tested that, and does not work.. Moreso, the code checks "if (error)", which if set to [NSNull null] will always fire; which is not the path to be tested.. – cyrix Aug 08 '16 at 16:29
  • 5
    The code in OCMock will not pass on the `NSNull` instance. It will replace it with `nil` (see: https://github.com/erikdoe/ocmock/blob/60c7b46bb571be15e511ab08dfa4f72c7fe92d6d/Source/OCMock/NSInvocation%2BOCMAdditions.m#L121-L132) Can you please check whether this really doesn't work? – Erik Doernenburg Aug 08 '16 at 22:25
3

Adding to the existing answers here, passing [NSNull null] does what you want in this case, which is passing nil as the param there.

I had a case (shown below) where my logic tested the existence of an error object OR my array was empty, and wanted my test to cover both cases and was afraid I'd only be able to test one case

if (error || array.count == 0) { // fail here }

Here is my test OCMock code:

NSArray *emptyArray = @[]; OCMStub([requestMock loadListWithCompletion:([OCMArg invokeBlockWithArgs:emptyArray, [NSNull null], nil])]);

...and in the actual invocation of that method, the error param (that I passed [NSNull null] into) was indeed nil, so the logic fell through to the empty array and the error case was still handled.

Mike
  • 9,765
  • 5
  • 34
  • 59
1

You can pass [NSNull null]. I just tested, it works.

Dan Flict
  • 117
  • 8