XCUITest发现多个匹配错误

时间:2016-09-12 10:49:15

标签: swift xcode-ui-testing

我正在为我的应用编写测试,需要找到按钮"查看2个更多优惠"我的页面上有多个这些按钮,但我只想点击一个。当我尝试这个时,会出现一个错误,"发现多个匹配" 所以问题是,我可以通过什么方式解决这个问题,以便我的测试只会搜索并点按其中一个名为"查看2个更多优惠"。

这是我目前的代码

let accordianButton = self.app.buttons["View 2 more offers"]
    if accordianButton.exists {
        accordianButton.tap()
    }
    sleep(1)
}

4 个答案:

答案 0 :(得分:27)

您应该使用更详细的方式来查询按钮,因为有多个按钮可以匹配它。

    // 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()
    }
斯威夫特4:

    let accordianButtonsQuery = self.app.buttons.matching(identifier: "View 2 more offers")
    if accordianButtonsQuery.count > 0 {
        let firstButton = accordianButtonsQuery.element(boundBy: 0)
        firstButton.tap()
    }

答案 1 :(得分:9)

有几种方法可以解决这个问题。

绝对索引

如果你绝对知道按钮将是屏幕上的第二个按钮,你可以通过索引访问它。

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()

答案 2 :(得分:7)

Xcode 9引入了firstMatch属性来解决此问题:

app.staticTexts["View 2 more offers"].firstMatch.tap()

答案 3 :(得分:0)

您应该使用matching,然后使用element,例如

let predicate = NSPredicate(format: "identifier CONTAINS 'Cat'")
let image = app.images.matching(predicate).element(boundBy: 0)