Search code examples
objective-cmockingocmock

Mocking a pointer to a pointer in Objective-C


I'm trying to mock a call to NSURLConnection. I swizzle the class method call with my own that calls my mock object. I'm trying to implement the mock like this:

[[[[urlConnectionMock expect] andDo:^(NSInvocation *invocation) {
    NSURLResponse * __autoreleasing *responsePointer;
    [invocation getArgument:&responsePointer atIndex:3];
    id response = [OCMockObject niceMockForClass:NSHTTPURLResponse.class];
    [[[response stub] andReturnValue:OCMOCK_VALUE((NSInteger){ 200 })] statusCode];
    *responsePointer = response;
}] andReturn:encryptedResponse] sendSynchronousRequest:OCMOCK_ANY returningResponse:OCMOCK_ANY error:OCMOCK_ANY];

The problem is that OCMOCK_ANY is an Objective-C pointer, not a pointer to a pointer (the compiler rightly complains). Before I dig more deeply into the OCMock source, perhaps someone can suggest how to get around this? Full credit given if you have a better approach entirely.


Solution

  • Figured it out. By-reference is already built into OCMock.

    id fakeResponse = [OCMockObject niceMockForClass:NSHTTPURLResponse.class];
    [[[fakeResponse stub] andReturnValue:OCMOCK_VALUE((NSInteger){ 200 })] statusCode];
    [[[urlConnectionMock expect] andReturn:encryptedResponse] sendSynchronousRequest:OCMOCK_ANY returningResponse:[OCMArg setTo:fakeResponse] error:[OCMArg setTo:nil]];
    

    This is so much happier looking as well!