如何使用 OCMock 测试是否在完成处理程序块内调用对象的方法? [英] How to test if a method of an object is called inside completion handler block using OCMock?
问题描述
我有一个方法:
@implementation SomeClass
- (void)thisMethod:(ObjectA *)objA {
[APIClient connectToAPIWithCompletionHandler:^(id result){
if (result) [objA methodOne];
else [objA methodTwo];
}];
}
有没有办法验证 methodOne
或 methodTwo
在调用 thisMethod:
时会被调用?基本上我只想存根那个 connectToAPIWithCompletionHandler:
方法.现在我可以通过 swizzling connectToAPIWithCompletionHandler:
方法来做到这一点.但我想知道是否有更好的方法.
Is there a way to verify methodOne
or methodTwo
will be called when thisMethod:
is called? Basically I just want to stub that connectToAPIWithCompletionHandler:
method. Right now I can do this by swizzling connectToAPIWithCompletionHandler:
method. But I want to know if there's better way.
我在这里发现了类似的问题,但在我的情况下它使用的是实例方法是类方法.
I found similar question here, but it's using instance method while in my case is class method.
推荐答案
试试这个:
- (void)test_thisMethod {
id mockA = [OCMockObject mockForClass:[ObjectA class]];
id mockClient = [OCMockObject mockForClass:[APIClient class]];
// Use class method mocking on APIClient
[[mockClient expect] andDo:(NSInvocation *invocation) {
void (^completion)(id result) = [invocation getArgumentAtIndexAsObject:2];
completion(nil);
}] connectToAPIWithCompletionHandler:OCMOCK_ANY];
[[mockA expect] methodTwo];
[[SomeClass new] thisMethod:mockA];
[mockA verify];
[mockClient verify];
}
请注意,我是直接在浏览器中输入的,但希望它可以正常工作.
Note that I typed this direct into the browser, but hopefully it's close to working.
这篇关于如何使用 OCMock 测试是否在完成处理程序块内调用对象的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!