ocmock

How to stub a class method with response block using OCMock


HTTPResult *successResult = [[HTTPResult alloc] init];
successResult.success = YES;
successResult.content = @{@"key":@"value"};

id httpMock = OCMClassMock([HTTPUtility class]);

OCMStub(ClassMethod([httpMock requestWithHTTPMethod:HTTPRequestMethodGet                        
    URLString:@"testURL"
    parameters:[OCMArg any]
response:[OCMArg any]])).andDo(^(NSInvocation *invocation) {
            void(^response)(HTTPResult *) = nil;
            [invocation getArgument:&response atIndex:5];
            response(successResult);
        });

this throw EXC_BAD_ACCESS in the[OCMockObject dealloc]method and crash when the class method is invoked

what's the right way to test a class method with a specific block


Solution

  • It looks like you want to capture the response argument block passed into the class method (without knowing the signature of the method I can't be sure), so instead of using [OCMArg any], you can check the argument with a block. See Section 4.3 here.

    [OCMArg checkWithBlock:^BOOL(id value) { /* return YES if value is ok */ }]
    

    So in your example:

    OCMStub(ClassMethod([httpMock requestWithHTTPMethod:HTTPRequestMethodGet                        
        URLString:@"testURL"
        parameters:[OCMArg any]
        response:[OCMArg checkWithBlock:^BOOL(HTTPResult *response) {
            response(successResult);
            return YES; // Replace this with a check for whether response is valid.
        }]);