我有一个应用程序,我在其中推送带有几个自定义 UIAlertControllerUIAlertAction 。每个 UIAlertActionactionWithTitle:style:handler: 的处理程序块中执行独特的任务。

我有几个需要验证的方法是在这些块中执行的。

如何执行 handler 块以便我可以验证这些方法是否已执行?

最佳答案

经过一番折腾,我终于弄明白了。结果证明 handler 块可以转换为函数指针,并且可以执行函数指针。

像这样

UIAlertAction *action = myAlertController.actions[0];
void (^someBlock)(id obj) = [action valueForKey:@"handler"];
someBlock(action);

这是一个如何使用它的示例。
-(void)test_verifyThatIfUserSelectsTheFirstActionOfMyAlertControllerSomeMethodIsCalled {

    //Setup expectations
    [[_partialMockViewController expect] someMethod];

    //When the UIAlertController is presented automatically simulate a "tap" of the first button
    [[_partialMockViewController stub] presentViewController:[OCMArg checkWithBlock:^BOOL(id obj) {

        XCTAssert([obj isKindOfClass:[UIAlertController class]]);

        UIAlertController *alert = (UIAlertController*)obj;

        //Get the first button
        UIAlertAction *action = alert.actions[0];

        //Cast the pointer of the handle block into a form that we can execute
        void (^someBlock)(id obj) = [action valueForKey:@"handler"];

        //Execute the code of the join button
        someBlock(action);
    }]
                                         animated:YES
                                       completion:nil];

   //Execute the method that displays the UIAlertController
   [_viewControllerUnderTest methodThatDisplaysAlertController];

   //Verify that |someMethod| was executed
   [_partialMockViewController verify];
}

关于ios - 如何使用 OCMock 测试 UIAlertAction 处理程序的内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36926827/

10-13 08:43