UITesting:设置accessibilityIdentifier属性

首先为控件添加accessibilityIdentifier属性,以最常见的button为例:

_leftButton.accessibilityIdentifier = @"live_broadcast button";

以test为方法名前缀,写个点击的小测试:

- (void)testStartLiving{
    //这里给个重新启动,若不需要,可去掉这行
    [self setUp];
    //循环点击10次
    for (int i = 0; i < 10; i ++) {
        [self startLivingApplication];
    }
}

- (void)startLivingApplication{
    //获取当前的window和所有控件
    XCUIApplication *app = [[XCUIApplication alloc] init];
    XCUIElement *windown = app.windows.allElementsBoundByIndex[0];

    XCUIElement *liveBroadcastButtonButton = app.buttons[@"live_broadcast button"];
    //私有方法,判断是否可点击
    if ([self canOperateElement:liveBroadcastButtonButton];) {
        [liveBroadcastButtonButton pressForDuration:2.0];
    }
}

- (BOOL)canOperateElement:(XCUIElement *)element{
    if (element != nil) {
        if (element.exists) {
            if (element.hittable) {
                return YES;
            }
        }
    }
    return NO;
}

至此,一个简单的点击操作就完成了。

备注:
1、关于canOperateElement方法,是为了防止点击了不存在或者无法点击的控件,发生错误;
2、若出现以下错误,说明当前想要操作的控件不再可视范围内,这个错误暂时没有明确的解决方法;

failed: UI Testing Failure - Failed to scroll to visible (by AX action) Button 0x12e762170: traits: 8589934593, {{9.0, 24.0}, {47.5, 32.0}}, label: 'Button', error: Error -25204 performing AXAction 2003

可能出现的原因有:
(1)当前view图层过于复杂,控件布局混乱,点击时触发了其他控件;
(2)当前view没有完全显示,找到了预期想要操作的控件,但是当前不能点击。
尝试以下方法来解决这个问题:

    NSPredicate *existPredicate = [NSPredicate predicateWithFormat:@"exists == true"];
    [self expectationForPredicate:existPredicate evaluatedWithObject:liveBroadcastButtonButton handler:nil];
    
    //直播按钮页 view弹出预留时间
    if (![self canOperateElement:liveBroadcastButtonButton]) {
        //强制点击操作
        [liveBroadcastButtonButton customTapElement:CGVectorMake(0.0, 0) pressDuration:4.0];
    }else{
        [liveBroadcastButtonButton tap];
    }
    [self waitForExpectationsWithTimeout:5 handler:nil];
    

你可能感兴趣的:(UITesting:设置accessibilityIdentifier属性)