【问题标题】:how to properly error handle XCUI element not found in swift如何正确错误处理 swift 中未找到的 XCUI 元素
【发布时间】:2016-03-29 15:23:57
【问题描述】:

我正在尝试为使用 XCUI 测试的 iOS UI 测试快速编写一个 do-try-catch。我正在阅读错误处理部分:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42-ID508 但是我不确定当找不到元素时应该抛出哪个错误。

func tapElement(string:String) throws {

    do{
        waitFor(app.staticTexts[string], 5)
        try app.staticTexts[string].tap()
    }
    catch {
        NSLog("Element was not found: \(string)")
        //how can i check specifically that the element was not found?
    }


}

....

func waitFor(element:XCUIElement, seconds waitSeconds:Double) {
    NSLog("Waiting for element: \(element)")
    let exists = NSPredicate(format: "exists == 1")
    expectationForPredicate(exists, evaluatedWithObject: element, handler: nil)
    waitForExpectationsWithTimeout(waitSeconds, handler: nil)
}

非常感谢任何帮助!

【问题讨论】:

    标签: ios swift xcode-ui-testing


    【解决方案1】:

    你应该使用element.exists和element.isHittable

    element.exists检查元素是否是UIApplication/ScrollView/..的元素。

    element.isHittable 确定是否可以计算元素的命中点。

    如果您不检查两者,element.tap() 会抛出以下错误,例如,如果元素位于 键盘 下:

    失败:无法滚动到可见(通过 AX 操作)TextField,...

    示例代码:

    let textField = elementsQuery.textFields.allElementsBoundByIndex[i]
    
    if textField.exists && textField.isHittable {
        textField.tap()
    } else {
         // text field is not hittable or doesn't exist!
         XCTFail()
     }
    

    【讨论】:

      【解决方案2】:

      您不需要在 UI 测试中尝试捕获元素。在尝试tap() 之前询问框架是否元素exists()。

      let app = XCUIApplication()
      let element = app.staticTexts["item"]
      if element.exists {
          element.tap()
      } else {
          NSLog("Element does not exist")
      }
      

      查看我的blog post on getting started with UI Testing 了解更多具体示例,like tapping an button。

      【讨论】:

      • 有时我想在找不到元素时优雅地处理
      • 我已经阅读了您的博客,感谢它是一个很好的来源。但我不是在寻找关于点击按钮的建议。任何有关使用 try catch 优雅地处理错误的见解将不胜感激
      • 为什么你要赶上?查看我的编辑以检查元素是否存在。
      • 我认为这可能是一个更好的方法,但你放在那里的实际上是我最终做的。谢谢!
      猜你喜欢
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-09
      • 2017-03-13
      • 2011-12-04
      • 1970-01-01
      相关资源
      最近更新 更多