【问题标题】:Wait for all HTTP requests to finish in XCode UI tests?等待所有 HTTP 请求在 XCode UI 测试中完成?
【发布时间】:2016-03-31 02:21:41
【问题描述】:

在 XCode 中测试 UI 时,有没有办法等待所有网络请求完成?

我有一个应用程序,它发送 HTTP 请求以从服务器获取一些数据,并且在 UI 测试中,我想在继续之前等待检索这些数据。目前我正在使用sleep(1),但这种方法似乎并不可靠。

【问题讨论】:

    标签: ios xcode swift xcode-ui-testing ui-testing


    【解决方案1】:

    最好的办法是等待一些 UI 元素出现或消失。这样想:

    框架就像一个用户。它不关心幕后运行的是什么代码。唯一重要的是屏幕上可见的内容。

    也就是说,您可以在 UI 测试中使用wait for a label titled "Go!" to appear

    let app = XCUIApplication()
    let goLabel = self.app.staticTexts["Go!"]
    XCTAssertFalse(goLabel.exists)
    
    let exists = NSPredicate(format: "exists == true")
    expectationForPredicate(exists, evaluatedWithObject: goLabel, handler: nil)
    
    app.buttons["Ready, set..."].tap()
    waitForExpectationsWithTimeout(5, handler: nil)
    XCTAssert(goLabel.exists)
    

    您也可以extract that into a helper method。如果您使用一些 Swift 编译器魔法,您甚至可以在 调用该方法的行上显示失败消息。

    private fund waitForElementToAppear(element: XCUIElement, file: String = #file, line: UInt = #line) {
        let existsPredicate = NSPredicate(format: "exists == true")
        expectationForPredicate(existsPredicate, evaluatedWithObject: element, handler: nil)
    
        waitForExpectationsWithTimeout(5) { (error) -> Void in
            if (error != nil) {
                let message = "Failed to find \(element) after 5 seconds."
                self.recordFailureWithDescription(message, inFile: file, atLine: line, expected: true)
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用委托或完成块设置您的方法,并在您的测试用例中使用XCTestExpectation,当数据返回时您可以使用fulfill

      【讨论】:

        猜你喜欢
        • 2015-04-17
        • 1970-01-01
        • 2018-07-19
        • 2017-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-26
        • 1970-01-01
        相关资源
        最近更新 更多