【问题标题】:How do I get the number of elements matching an identifier, say "fooImage" returned by an XCUIQuery?如何获取与标识符匹配的元素数量,例如 XCUIQuery 返回的“fooImage”?
【发布时间】:2018-02-28 18:14:52
【问题描述】:

假设我有一张包含三张图片的表格,其 accessiblityIdentifier 设置为“fooImage”。

XCTAssertTrue(table["tableName"].images.count == 3) 可以,但这很糟糕——如果有人添加了另一种图像类型怎么办?我想要标识符 == "fooImage" 的所有图像的计数。

XCUIApplication().images["fooImage"].countValue of type 'XCUIElement' has no member 'count' 的编译失败。

【问题讨论】:

    标签: xcode-ui-testing uitest xcuitest


    【解决方案1】:

    XCUIElementQuery 上使用下标会给你一个XCUIElement,它没有count 属性。你想像这样在XCUIElementQuery 上使用count

    XCUIApplication().images.matching(identifier: "fooImage").count
    

    【讨论】:

      【解决方案2】:

      为了允许 XCUIElement 这样做,它有一个私有的 query getter。由于私有 API 仅用于 UI 测试(因此不会嵌入到应用程序中),因此不存在被拒绝的风险,它仍然容易受到内部更改的影响,因此如果您知道这是什么,请使用意思。

      以下扩展可用于添加想要的行为:

      extension XCUIElement {
          @nonobjc var query: XCUIElementQuery? {
              final class QueryGetterHelper { // Used to allow compilation of the `responds(to:)` below
                  @objc var query: XCUIElementQuery?
              }
      
              if !self.responds(to: #selector(getter: QueryGetterHelper.query)) {
                  XCTFail("Internal interface changed: tests needs updating")
                  return nil
              }
              return self.value(forKey: "query") as? XCUIElementQuery
          }
      
          @nonobjc var count: Int {
              return self.query?.count ?? 0
          }
      }
      

      如果内部接口发生变化(如果内部query getter 被重命名),扩展将无法通过测试,防止测试突然无法在没有解释的情况下工作(此代码已使用当时可用的最新 Xcode 进行测试, Xcode 10 beta 6)。

      添加扩展后,问题XCUIApplication().images["fooImage"].count 中的代码将编译并具有预期的行为。

      【讨论】:

        猜你喜欢
        • 2016-06-02
        • 2018-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-07
        • 1970-01-01
        相关资源
        最近更新 更多