我正在为我的应用程序编写测试,并需要找到按钮“查看2更多的优惠”,有多个按钮在我的页面上,但我只想点击一个。当我尝试这样做时,出现了一个错误,上面写着“找到了多个匹配”,所以问题是,我能用什么方法绕过这个问题,这样我的测试就只会搜索和点击一个名为“查看2多个报价”的按钮。
这是我目前的代码
let accordianButton = self.app.buttons["View 2 more offers"]
if accordianButton.exists {
accordianButton.tap()
}
sleep(1)
}发布于 2016-09-12 11:37:58
您应该使用一种更详细的方式来查询您的按钮,因为有多个匹配它的按钮。
// We fetch all buttons matching "View 2 more offers" (accordianButtonsQuery is a XCUIElementQuery)
let accordianButtonsQuery = self.app.buttons.matchingIdentifier("View 2 more offers")
// If there is at least one
if accordianButtonsQuery.count > 0 {
// We take the first one and tap it
let firstButton = accordianButtonsQuery.elementBoundByIndex(0)
firstButton.tap()
}Swift 4:
let accordianButtonsQuery = self.app.buttons.matching(identifier: "View 2 more offers")
if accordianButtonsQuery.count > 0 {
let firstButton = accordianButtonsQuery.element(boundBy: 0)
firstButton.tap()
}发布于 2016-09-12 11:38:52
解决这个问题有几种方法。
绝对索引
如果您绝对知道该按钮将是屏幕上的第二个按钮,您可以通过索引访问它。
XCUIApplication().buttons.element(boundBy: 1)
但是,当按钮在屏幕上移动或添加其他按钮时,您可能必须更新查询。
可访问性更新
如果您可以访问生产代码,则可以更改按钮上的accessibilityTitle。将其更改为比标题文本更具体的内容,然后使用新标题通过测试访问按钮。此属性仅用于测试,在从屏幕上读取时不会显示给用户。
更具体的查询
如果这两个按钮嵌套在其他UI元素中,则可以编写更具体的查询。例如,假设每个按钮位于表视图单元格内。可以将可访问性添加到表单元格中,然后查询按钮。
let app = XCUIApplication()
app.cells["First Cell"].buttons["View 2 more offers"].tap()
app.cells["Second Cell"].buttons["View 2 more offers"].tap()发布于 2017-08-08 12:52:15
Xcode 9引入了一个firstMatch属性来解决这个问题:
app.staticTexts["View 2 more offers"].firstMatch.tap()https://stackoverflow.com/questions/39448630
复制相似问题