【问题标题】:UI Testing Assertion as Utility Method doesn't return failure (Xcode 8, Swift 3)UI 测试断言作为实用方法不返回失败(Xcode 8、Swift 3)
【发布时间】:2017-08-12 01:26:10
【问题描述】:

从这个website 窃取帮助,我已经实现了这个修复来运行一个小的等待功能,所以我可以确保我等待元素/页面/等。在继续测试之前加载。如果我直接在测试中使用该代码,则该修复工作有效,但是当我将它放在另一个类的实用方法中时,它不会返回正确的通过/失败结果。

问题出在运行以下代码时:

func testCreateGame() {
    let app = LauncherUtilityMethods.startApp()
    AllStageUtilityMethods().waitForElement(app.buttons["THISDOESNOTEXIST"])

此元素不存在,但我仍会看到测试通过。 下面是实用方法:

    func waitForElement(_ element: XCUIElement, file: String = #file, line: UInt = #line) {
    let exists = NSPredicate(format: "exists == true")
    expectation(for: exists, evaluatedWith: element, handler: nil)

    waitForExpectations(timeout: 5) { (error) -> Void in
        if (error != nil) {
            let message = "Failed to find \(element) after 5 seconds."
            self.recordFailure(withDescription: message, inFile: file, atLine: line, expected: true)
            XCTFail()
        }
    }

在 if 语句中插入直接 XCTFail( ) 后,测试将相应地失败/通过。有没有更好的方法来处理这种情况?两次有效地未能通过我的测试似乎是多余的,但只有一次通过实际显示为失败。

我想我可以在 XCTFail 上添加一个描述,但与实际的 .recordFailure 选项相比,这是一种不太优雅的方法。 感谢您的帮助!

【问题讨论】:

    标签: swift3 xcode8 xctest xcode-ui-testing


    【解决方案1】:

    我建议在 XCTestCase 本身上创建该实用程序方法,以便它具有正在运行的测试用例的上下文。所有断言都需要测试用例通过或失败。这是示例代码。

    extension XCTestCase {
    
    func waitForElementToAppear(element: XCUIElement, timeOut: Double  = 5) {
        let existsPredicate = NSPredicate(format: "exists == true")
        expectation(for: existsPredicate,
                    evaluatedWith: element, handler: nil)
        waitForExpectations(timeout: timeOut, handler: nil)
    }
    
    
    func waitForElementToDisappear(element: XCUIElement){
        let doesNotExistPredicate = NSPredicate(format: "exists == false")
        expectation(for: doesNotExistPredicate,
                    evaluatedWith: element, handler: nil)
        self.waitForExpectations(timeout: 50) { error in
            sleep(1)
        }
     }   
    }
    

    你可以像下面这样调用

       testCase.waitForElementToAppear(element: signOutButton)
    

    【讨论】:

    • 实现梦想。谢谢!我还没有测试 waitForElementToDisappear 代码,但是我将你的代码和我的代码进行了小组合,以获得我喜欢的错误消息(在测试本身上)
    • 很高兴有帮助:)
    猜你喜欢
    • 2016-02-29
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2014-10-03
    相关资源
    最近更新 更多