【问题标题】:Appium: How to iterate over a listview of unknown length?Appium:如何迭代未知长度的列表视图?
【发布时间】:2017-12-30 14:25:13
【问题描述】:

我有一个列表视图,它具有我理论上不知道的层次结构。我试图接受一个字符串数组并为其中的每个字符串创建 MobileElements,但是由于我通过注释自动定义我的元素的方式(PageFactory),它们不能使用变量。我也不知道在方法中定义我的注释是否有效或正确。

我写的代码,显然不能编译如下:

public void selectLocation(String[] location) {

    List<MobileElement> locationsList = new ArrayList<>();
    for(int i = 0; i < location.length; i++) {

        @iOSFindBy(accessibility = location[i])
        @AndroidFindBy(xpath = "//android.widget.TextView[@text='" + location[i] + "']")
        locationsList.add(i);
    }
    for (int i = 0; i < location.length; i++) {
        locationsList.get(i).click();
    }
}

我假设执行此操作的正确方法与我实施的方法完全不同。

我的列表层次结构类似于以下内容;我的终点可能会因我走的分支而异:

  • 大陆 1
    • 城市 1
      • 1号房间
      • 2号房间
    • 城市2
      • 1号楼
        • 1号房间
        • 2号房间
      • 2号楼
        • 1号房间
        • 2号房间

【问题讨论】:

    标签: java appium appium-ios


    【解决方案1】:

    我现在寻找一个匹配的元素。如果我没有找到它,我会在列表中进一步滑动。如果该元素不存在,我显然会遇到问题,但在我的情况下并不是真正的问题,因为那将是一个失败的测试。

    while (!driver.findElementById(currentLocation).isDisplayed()) {
       driver.swipe(startX, startY, startX, endY, 100);
    }
    driver.findElementById(currentLocation).click();
    

    是的,我也意识到 .swipe() 已被弃用,但它仍然适用于我,我宁愿在必要之前不要用 TouchActions 重写我的所有代码。

    【讨论】:

      【解决方案2】:

      我最终使用“FindsBys”函数创建了一个包含所有匹配元素的数组。然后我循环遍历这些元素,寻找与我的字符串之一匹配的内容。

      @AndroidFindBys({@AndroidFindBy(xpath = "//android.widget.TextView")})
      @iOSFindBys({@iOSFindBy(xpath = "//XCUIElementTypeStaticText")})
      private List<MobileElement> locationsList;
      
      ...
      
      public void selectLocation(String[] location)
      {
          for(int i = 0; i < locationsList.size(); i++)
              for(int p = 0; p < location.length; p++) {
                  if (locationsList.get(i).getText().equals(location[p])) {
                      locationsList.get(i).click();
                  }
              }
      }
      

      这不是万无一失的(如果您在层次结构的不同级别有重复的字符串,您可能会遇到问题),但它适用于我的用例,并且应该能够指导任何寻求更强大解决方案的人。

      【讨论】:

      • 我会,但这是一个糟糕的答案,因为它没有考虑到需要滚动才能看到元素的 ListView。
      【解决方案3】:

      你可以循环遍历元素本身。

      ....

      for(MobileElement location: locationsList) {
          for(int p = 0; p < location.length; p++) {
              if (location.getText().equals(location[p])) {
                  location.click();
              }
          }
      }
      

      【讨论】:

      • 你是对的。我不得不按我的方式编写它,因为我通过 Xpath 构建的列表比预期的要大,因为我找到了我不想要的元素。在这方面工作了几个月并总体上学习了 Appium 之后,我已经完全重构了代码并把它扔掉了:)
      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 2018-02-02
      • 2012-04-16
      • 1970-01-01
      • 2014-10-03
      • 2021-11-12
      • 2017-10-15
      • 1970-01-01
      相关资源
      最近更新 更多