Obj-C:如何从NSInvocation获取并调用块参数 - 在iOS上存根Twitter帐户

Jon*_*ian 3 objective-c ocmock ios objective-c-blocks ios5

我正在使用KIF和OCMock测试iOS应用程序,将设备存根ACAccountStore以返回我自己的Twitter帐户表示.我想要存根requestAccessToAccountsWithType,并使用我自己的值调用传递的完成处理程序,但我似乎无法从调用中获取块并正确调用它(EXC_BAD_ACCESS).作为Objective-C和iOS的新手,我确信自己做错了什么,同时把这个块拉出来NSInvocation.

这是生产代码._accountStore是从测试设置中注入的.

ACAccountType *twitterType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[_accountStore requestAccessToAccountsWithType:twitterType withCompletionHandler:^(BOOL granted, NSError *error) {
    NSLog(@"authorized=%i in block", granted);
    // important code here
}];
Run Code Online (Sandbox Code Playgroud)

测试设置代码.

ACAccountStore *realStore = [[ACAccountStore alloc] init];
// Stub the store to return our stubbed Twitter Account
id mockStore = [OCMockObject partialMockForObject:realStore];
[[[mockStore stub] andDo:^(NSInvocation *invocation) {
    void (^grantBlock)(BOOL granted, NSError *error) = nil;
    [invocation getArgument:&grantBlock atIndex:1]; // EXC_BAD_ACCESS
    grantBlock(TRUE, nil); // run the important code with TRUE
}] requestAccessToAccountsWithType:[OCMArg any] withCompletionHandler:[OCMArg any]];
// not shown: inject the mockStore into production code
Run Code Online (Sandbox Code Playgroud)

Dav*_*ong 9

我认为你应该使用索引3,而不是1.索引0是self,索引1是_cmd.