2

I have a method that calls a request with a response block inside. I want to stub my response and return fake data. How can this be done?

-(void)method:(NSString*)arg1{

    NSURLRequest *myRequest = ...........
    [self request:myRequest withCompletion:^(NSDictionary* responseDictionary){

    //Do something with responseDictionary <--- I want to fake my responseDictionary

    }];
}

- (void)request:(NSURLRequest*)request withCompletion:(void(^)(NSDictionary* responseDictionary))completion{

    //make a request and passing a dictionary to completion block 

    completion(dictionary);

}
Rafał Sroka
  • 39,540
  • 23
  • 113
  • 143
iamarnold
  • 705
  • 1
  • 8
  • 22
  • 1
    Possible duplicate of [Can OCMock run a block parameter?](http://stackoverflow.com/questions/16530194/can-ocmock-run-a-block-parameter) – e1985 Mar 10 '16 at 14:03

1 Answers1

1

If I understand you correctly, you want to mock request:withCompletion: and call the passed completion block.

Here is how I have done this in the past. I've adapted this code to your call, but I cannot check it for compilation errors, but it should show you how to do it.

id mockMyObj = OCClassMock(...);
OCMStub([mockMyObj request:[OCMArg any] completion:[OCMArg any]])).andDo(^(NSInvocation *invocation) {

    /// Generate the results
    NSDictionary *results = .... 

    // Get the block from the call.
    void (^__unsafe_unretained completionBlock)(NSDictionary* responseDictionary);
    [invocation getArgument:&callback atIndex:3];

    // Call the block.
    completionBlock(results);
});

You will need the __unsafe_unretained or things will go wrong. Can't remember what right now. You could also combine this with argument captures as well if you wanted to verify the passed arguments such as the setup of the request.

drekka
  • 20,957
  • 14
  • 79
  • 135