XCUITest Multiple matches found 错误

XCUITest Multiple matches found error

我正在为我的应用程序编写测试,需要找到按钮 "View 2 more offers" 我的页面上有多个这样的按钮,但我只想单击一个。当我尝试这个时,出现错误 "Multiple matches found" 所以问题是,我可以用什么方法解决这个问题,以便我的测试只搜索并点击名为 "View 2 more offers".

的按钮之一

这是我当前的代码

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

您应该使用一种更详细的方式来查询您的按钮,因为匹配它的按钮不止一个。

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

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

绝对索引

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

XCUIApplication().buttons.element(boundBy: 1)

但是,每当按钮在屏幕上移动或添加其他按钮时,您可能必须更新查询。

辅助功能更新

如果您有权访问生产代码,则可以更改按钮上的 accessibilityTitle。将其更改为比标题文本更具体的内容,然后使用新标题通过测试访问按钮。此 属性 仅显示用于测试,不会在屏幕外阅读时显示给用户。

更具体的查询

如果这两个按钮嵌套在其他 UI 元素中,您可以编写更具体的查询。例如,假设每个按钮都在 table 视图单元格内。您可以向 table 单元格添加辅助功能,然后查询按钮。

let app = XCUIApplication()
app.cells["First Cell"].buttons["View 2 more offers"].tap()
app.cells["Second Cell"].buttons["View 2 more offers"].tap()

你应该使用 matching,然后 element,比如

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

Xcode 9引入一个firstMatch 属性来解决这个问题:

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