首先為控件添加accessibilityIdentifier屬性,以最常見的button為例:
_leftButton.accessibilityIdentifier = @"live_broadcast button";
以test為方法名前綴,寫個(gè)點(diǎn)擊的小測(cè)試:
- (void)testStartLiving{
//這里給個(gè)重新啟動(dòng),若不需要,可去掉這行
[self setUp];
//循環(huán)點(diǎ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"];
//私有方法,判斷是否可點(diǎn)擊
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;
}
至此,一個(gè)簡單的點(diǎn)擊操作就完成了。
備注:
1、關(guān)于canOperateElement方法,是為了防止點(diǎn)擊了不存在或者無法點(diǎn)擊的控件,發(fā)生錯(cuò)誤;
2、若出現(xiàn)以下錯(cuò)誤,說明當(dāng)前想要操作的控件不再可視范圍內(nèi),這個(gè)錯(cuò)誤暫時(shí)沒有明確的解決方法;
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ù)雜,控件布局混亂,點(diǎn)擊時(shí)觸發(fā)了其他控件;
(2)當(dāng)前view沒有完全顯示,找到了預(yù)期想要操作的控件,但是當(dāng)前不能點(diǎn)擊。
嘗試以下方法來解決這個(gè)問題:
NSPredicate *existPredicate = [NSPredicate predicateWithFormat:@"exists == true"];
[self expectationForPredicate:existPredicate evaluatedWithObject:liveBroadcastButtonButton handler:nil];
//直播按鈕頁 view彈出預(yù)留時(shí)間
if (![self canOperateElement:liveBroadcastButtonButton]) {
//強(qiáng)制點(diǎn)擊操作
[liveBroadcastButtonButton customTapElement:CGVectorMake(0.0, 0) pressDuration:4.0];
}else{
[liveBroadcastButtonButton tap];
}
[self waitForExpectationsWithTimeout:5 handler:nil];