简体   繁体   English

如何正确处理未在swift中找到的XCUI元素

[英]how to properly error handle XCUI element not found in swift

I am trying to write a do-try-catch in swift for my iOS UI test which uses XCUI testing. 我正在尝试为使用XCUI测试的iOS UI测试快速编写一次do-try-catch。 I am reading the error-handling section: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42-ID508 but am unsure of which error should be thrown when an element is not found. 我正在阅读错误处理部分: 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)
}

any help greatly appreciated!! 任何帮助,不胜感激!

You should use element.exists AND element.isHittable 您应该使用element.exists AND element.isHittable

element.exists checks whether the element is an element of the UIApplication/ScrollView/.. element.exists检查该元素是否为UIApplication / ScrollView /的元素。

element.isHittable determines if a hit point can be computed for the element. element.isHittable确定是否可以为元素计算出生命值。

If you don't check for both, than element.tap() throws the following error, for example, if the element is under the keyboard : 如果您没有同时检查两者,那么element.tap()会引发以下错误,例如,如果元素在键盘下

Failed: Failed to scroll to visible (by AX action) TextField,... 失败:无法滚动到可见(通过AX操作)TextField,...

Example code: 示例代码:

let textField = elementsQuery.textFields.allElementsBoundByIndex[i]

if textField.exists && textField.isHittable {
    textField.tap()
} else {
     // text field is not hittable or doesn't exist!
     XCTFail()
 }

You shouldn't need to try-catch finding elements in UI Testing. 您无需在UI测试中尝试捕获发现元素。 Ask the framework if the element exists() before trying to tap() it. 在尝试tap()元素之前,请询问框架该元素是否exists()

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

Check out my blog post on getting started with UI Testing for more specific examples, like tapping an button . 查看我有关UI测试入门的博客文章,了解更多具体示例, 例如点击按钮

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM