首先為控件添加accessibilityIdentifier屬性癣籽,以最常見的button為例:
_leftButton.accessibilityIdentifier = @"live_broadcast button";
以test為方法名前綴,寫個點擊的小測試:
- (void)testStartLiving{
//這里給個重新啟動帆精,若不需要叉弦,可去掉這行
[self setUp];
//循環(huán)點擊10次
for (int i = 0; i < 10; i ++) {
[self startLivingApplication];
}
}
- (void)startLivingApplication{
//獲取當(dāng)前的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、關(guān)于canOperateElement方法庐船,是為了防止點擊了不存在或者無法點擊的控件银酬,發(fā)生錯誤;
2筐钟、若出現(xiàn)以下錯誤揩瞪,說明當(dāng)前想要操作的控件不再可視范圍內(nèi),這個錯誤暫時沒有明確的解決方法篓冲;
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
可能出現(xiàn)的原因有:
(1)當(dāng)前view圖層過于復(fù)雜李破,控件布局混亂,點擊時觸發(fā)了其他控件壹将;
(2)當(dāng)前view沒有完全顯示嗤攻,找到了預(yù)期想要操作的控件,但是當(dāng)前不能點擊诽俯。
嘗試以下方法來解決這個問題:
NSPredicate *existPredicate = [NSPredicate predicateWithFormat:@"exists == true"];
[self expectationForPredicate:existPredicate evaluatedWithObject:liveBroadcastButtonButton handler:nil];
//直播按鈕頁 view彈出預(yù)留時間
if (![self canOperateElement:liveBroadcastButtonButton]) {
//強制點擊操作
[liveBroadcastButtonButton customTapElement:CGVectorMake(0.0, 0) pressDuration:4.0];
}else{
[liveBroadcastButtonButton tap];
}
[self waitForExpectationsWithTimeout:5 handler:nil];