XCUITest发现多个匹配错误

Bil*_*oyo 15 swift xcode-ui-testing

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

这是我目前的代码

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

Jul*_*ere 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()
    }
Run Code Online (Sandbox Code Playgroud)

斯威夫特4:

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


Joe*_*tti 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()
Run Code Online (Sandbox Code Playgroud)

  • 感谢您提供文档,您自己需要更多地指定查询.BTW在博客上做得很好,最近在学习测试的同时帮助了自己很多! (2认同)

Xav*_*ler 8

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

app.staticTexts["View 2 more offers"].firstMatch.tap()
Run Code Online (Sandbox Code Playgroud)