如何使用OCMock使用响应块存根方法

时间:2016-03-08 21:51:13

标签: ios objective-c block stub ocmock

我有一个方法可以调用带有响应块的请求。我想留下我的回复并返回虚假数据。怎么办呢?

-(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);

}

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你想模拟request:withCompletion:并调用传递的完成块。

以下是我过去的做法。我已将此代码调整为您的调用,但我无法检查编译错误,但它应该告诉您如何执行此操作。

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);
});

您需要__unsafe_unretained,否则会出错。现在不记得了。如果你想验证传递的参数,例如请求的设置,你也可以将它与参数捕获结合起来。

相关问题