我正在尝试从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()
}
}
答案 0 :(得分: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?中获得有关测试中放弃异步任务的更多信息。