【问题标题】:XCUITest Multiple matches found errorXCUITest Multiple match found 错误
【发布时间】:2017-01-19 19:00:21
【问题描述】:

我正在为我的应用编写测试,需要找到“查看更多优惠”按钮,我的页面上有多个这样的按钮,但我只想单击一个。当我尝试此操作时,出现错误提示“找到多个匹配项” 所以问题是,我有什么方法可以解决这个问题,以便我的测试将搜索并只点击一个名为“查看更多优惠”的按钮。

这是我当前的代码

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

【问题讨论】:

  • 这不是 XCTest,这是 XCUITest。
  • 您能否检查层次结构并查看是否存在多个元素?另外,您是否使 UIButton 可访问并赋予它与 UIButtonLabel 上相同的可访问性标签?
  • @gran_profaci ,您好,感谢您的帮助,是的,存在多个元素并且使用标签名称会导致相同的错误。你知道是否有办法让它选择元素类型的第一个按钮?

标签: swift xcode-ui-testing


【解决方案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()
    }

斯威夫特 4:

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

【讨论】:

  • 这已经解决了!谢谢!
  • 不客气。如果这个答案解决了您的问题,请mark it as accepted(点击旁边的复选标记)。
  • 如果您的测试在更新到 XCode 8.3 后开始失败,这将是因为之前的错误 fixed by Apple。 “修复了在处理 XCTestExpectations 时等待针对 XCUIElements 评估的谓词的错误。因此,一些先前成功的测试将开始失败,尽管有歧义(不正确)的查询。”
【解决方案2】:

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

绝对索引

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

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

【讨论】:

  • 感谢您提供的文档,您是正确的,我需要更多地指定查询。顺便说一句,在博客上做得很好,最近在学习测试的同时帮助了自己很多!
【解决方案3】:

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

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

【讨论】:

  • 我以前也这么认为,但在某处我读到 firstMatch 不是为此目的,并提到了 firstMatch 的文档developer.apple.com/documentation/xctest/… :)
  • 我喜欢这个解决方案,因为出于某种原因,即使我只有一个元素,我也会收到错误消息。
【解决方案4】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 2015-12-24
    • 2013-02-20
    • 2015-01-30
    相关资源
    最近更新 更多