如何使用 OCMock 测试 UIAlertAction 处理程序的内容

2024-02-28

我有一个应用程序,我可以在其中推送UIAlertController有几个定制的UIAlertActions。每个UIAlertAction在处理程序块中执行独特的任务actionWithTitle:style:handler:.

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

我怎样才能执行handler阻止以便我可以验证这些方法是否已执行?


经过一番玩弄后我终于弄清楚了。事实证明handlerblock 可以被转换为函数指针并且函数指针可以被执行。

Like so

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];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 OCMock 测试 UIAlertAction 处理程序的内容 的相关文章

随机推荐