首先為控件添加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];