【问题标题】:How to get index of XCUIElement in XCUIElementQuery?如何在 XCUIElementQuery 中获取 XCUIElement 的索引?
【发布时间】:2015-08-23 09:08:00
【问题描述】:

这是我的简单UITest(自定义tabbarcontroller中的标签顺序)

func testIsOrderOfTabsSaved() {

    let app = XCUIApplication()
    let tabBarsQuery = app.tabBars
    tabBarsQuery.buttons["More"].tap()
    app.navigationBars["More"].buttons["Edit"].tap()
    tabBarsQuery.buttons["Takeaway"].swipeLeft()
    tabBarsQuery.buttons["In Restaurant"].swipeLeft()

    //here, how to get position of moved button with text "In Restaurant"?

注意

可以通过索引从XCUIElementQuery获取XCUIElement。我可以反过来做吗?

【问题讨论】:

    标签: ios xcode swift xcode-ui-testing ui-testing


    【解决方案1】:

    查询似乎会根据屏幕上的位置自动按顺序返回。

    for i in 0...tabsQuery.buttons.count {
        let ele = tabsQuery.buttons.elementBoundByIndex(i)
    }
    

    其中索引i代表按钮在标签栏中的位置,0为最左边的标签,i == tabsQuery.buttons.count为最右边。

    【讨论】:

      【解决方案2】:

      您有多种方法来创建职位测试。最简单的方法是获取索引 0 和 1 处的按钮,然后按名称获取两个按钮并比较数组是否相等:(编写时无需测试)

       let buttonOrder = [tabBarsQuery.buttons.elementAtIndex(0), tabBarsQuery.buttons.elementAtIndex(1)]
      
       let takeawayButton = buttons["Takeaway"];
       let restaurantButton = buttons["In Restaurant"];
      
       XCTAssert(buttonOrder == [takeawayButton, restaurantButton])
      

      另一种选择是直接获取每个按钮的frame,并断言一个X坐标低于另一个。

      要回答您关于在XCUIElementQuery 中获取XCUIElement 的索引的具体问题,这绝对是可能的。只需遍历查询中的所有元素并返回与该元素相等的第一个元素的索引。

      【讨论】:

      • @netshark1000 谢谢,已更新为使用elementAtIndex
      【解决方案3】:

      单独的 XCUIElement 无法告诉您它在 XCUIElementQuery 中的位置。如果您对 XCUIElement 有所了解,则可以搜索 XCUIElementQuery 以发现其偏移量。在下面让我们假设“更多”是标识符(如果您正在使用,请将“标识符”更改为“标签”)。

      如果您想找到“更多”按钮的偏移量(如原始问题中所述),那么:

      var offsetWithinQuery : Int? = nil  // optional since it's possible the button isn't found.  
      for i in 0...tapBarsQuery.buttons.count{
          if tapBarsQuery.elementAtIndex(i).indentifier == "More" {
             offSetWithinQuery = i
      }
      

      上述循环退出后,您将获得偏移量,或者如果未找到“更多”,则偏移量为零。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-28
        • 2021-05-15
        相关资源
        最近更新 更多