我们正在尝试从UIAutomation迁移到XCUITests。 对于UIAutomation,我们想出了一个方便的tapOnName'通过整个子元素树爬行并使用第一个匹配点击元素的函数。
function log(msg) {
UIALogger.logDebug(msg);
}
//recursive function crawling thru an elements hierarchy
//and tapping on the first match of accessibilityIdentifier
//or button text
function tapOnNameWithRoot(name,el) {
if (el.name()==name && el.isVisible()) {
log("tap on itt!!!")
el.tap();
return true;
}
if (el.toString()=="[object UIAButton]" && el.label()==name) {
log("tap on Button!!!")
el.tap();
return true;
}
var elements=el.elements();
if (elements===null || elements===undefined) {
log("elements null or undefined for:"+el.toString());
return false;
}
for(var i=0,len=elements.length ;i<len;i++) {
if (tapOnNameWithRoot(name,elements[i])) {
return true;
}
}
return false;
}
var win = UIATarget.localTarget().frontMostApp().mainWindow();
//for ex taps on a button with the text "pushme" in the
//main UIWindow
tapOnNameWithRoot("pushme",win);
没问题:是否可以使用XCUIApplication实现相同的功能?
答案 0 :(得分:3)
XCTest中有对此功能的简写支持。
要从任何元素中点击第一个匹配项,您可以获取所有元素并点按第一个匹配项:
let app = XCUIApplication()
let element = app.descendentsMatchingType(.Any)["someIdentifier"]
element.tap()
如果您知道它将是什么类型的元素,最好先按该类型进行过滤:
let app = XCUIApplication()
let element = app.buttons["someIdentifier"]
element.tap()
答案 1 :(得分:2)
你在寻找这样的东西:
func tapBasedOnAccessibilityIdentifier(elementType elementType: XCUIElementQuery, accessibilityIdentifier: String) {
var isElementExist = false
for element in elementType.allElementsBoundByIndex {
if element.label == accessibilityIdentifier {
element.tap()
isElementExist = true
break
}
}
if !isElementExist {
XCTFail("Failed to find element")
}
}
您可以在测试中调用方法,如:
tapBasedOnAccessibilityIdentifier(elementType: app.staticTexts, accessibilityIdentifier: "Accessibility Identifier")
您可以稍微调整一下,以满足所有要求。