[英]How to stub method with response block using 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);
}
如果我对您的理解正确,则想模拟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
否则会出错。 现在不记得了。 如果您想验证传递的参数(例如请求的设置),也可以将其与参数捕获结合使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.