【问题标题】:getting output from URLSession in XCUITest从 XCUITest 中的 URLSession 获取输出
【发布时间】:2018-12-04 10:32:55
【问题描述】:

我正在尝试从 XCUI 测试中的 URL 获取值。但是它没有输出,所以我不确定除了我已经在下面的代码中尝试过之外我还应该做些什么:

import XCTest

class ExampleUITests: XCTestCase {


func testExample() {
    print("We are in XCUITest textExample right now")

    let urlString = "https://api.ipify.org/"
    guard let url = URL(string: urlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if error != nil {
            print(error!.localizedDescription)
        }

        guard let data = data
            else {
                print("error found in data")
                return
        }

        print("*******")
        let outputStr  = String(data: data, encoding: String.Encoding.utf8) as String!
        print (outputStr)

        }.resume()

}

}

【问题讨论】:

标签: swift xcode urlsession xcuitest


【解决方案1】:

问题是,测试完成后返回来自服务器的响应。您应该在测试中添加等待网络响应。

在测试开始时添加:

let expectation = expectationWithDescription("")

在测试结束时添加:

waitForExpectationsWithTimeout(5.0) { (error) in
    if error != nil {
        XCTFail(error.localizedDescription)
    }
}

并在网络完成块中添加:

expectation.fulfill()

您可以在测试中获取有关等待异步任务的更多信息,例如这里How can I get XCTest to wait for async calls in setUp before tests are run?

【讨论】:

    猜你喜欢
    • 2021-12-26
    • 1970-01-01
    • 2019-03-01
    • 2017-12-09
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多