ios - 未调用完成处理程序
问题描述
我从这个站点学到了相当全面的方法。我对其进行了一些定制以包含一个转义闭包,但它没有被调用,并且我没有在调用者级别收到任何响应。
我在所有警卫中设置了断点,以查看它是否在某个级别退出,但到目前为止还没有任何线索。
func getUsers(_ completion: @escaping (String?, NSException?) -> Void) {
guard let url = URL(string: "http://127.0.0.1:8080/employees") else {
completion(nil, NSException(name: NSExceptionName(rawValue: "Error"), reason: "Error validating URL.", userInfo: nil))
return
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
print("1")
completion(nil, NSException(name: NSExceptionName(rawValue: "Error"), reason: error?.localizedDescription, userInfo: nil))
return
}
guard let data = data else {
print("2")
completion(nil, NSException(name: NSExceptionName(rawValue: "Error"), reason: "Did not receive data.", userInfo: nil))
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
print("3")
completion(nil, NSException(name: NSExceptionName(rawValue: "Error"), reason: "HTTP request failed.", userInfo: nil))
return
}
do {
guard let jsonObject = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
completion(nil, NSException(name: NSExceptionName(rawValue: "Error"), reason: "Cannot convert data to JSON object.", userInfo: nil))
return
}
guard let prettyJsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) else {
completion(nil, NSException(name: NSExceptionName(rawValue: "Error"), reason: "Cannot convert JSON object to Pretty JSON data.", userInfo: nil))
return
}
guard let prettyPrintedJson = String(data: prettyJsonData, encoding: .utf8) else {
completion(nil, NSException(name: NSExceptionName(rawValue: "Error"), reason: "Could print JSON in String.", userInfo: nil))
return
}
print(prettyPrintedJson)
completion("done", nil)
} catch {
completion(nil, NSException(name: NSExceptionName(rawValue: "Error"), reason: "Trying to convert JSON data to string.", userInfo: nil))
return
}
}.resume()
}
用法
func testGetUsers() {
userData.getUsers {
print($0 ?? "result is nil")
print($1?.name ?? "error is nil")
}
}
Info.plist 设置
解决方案
在您的测试中,您将使用期望来等待调用闭包,例如
func testGetUsers() {
let e = expectation(description: "testGetUsers")
userData.getUsers {
print($0 ?? "result is nil")
print($1?.name ?? "error is nil")
e.fulfill()
}
waitForExpectations(timeout: 10)
}
在大多数圈子中,网络请求不被视为单元测试。通常我们会“模拟”网络响应并测试我们的应用程序处理各种类型响应的能力。单元测试的目标不是测试与后端的集成,而是测试它将如何处理各种理论响应。
推荐阅读
- flutter - Flutter:导航到另一个页面后列表项的数据丢失
- javascript - JavaScript - 按值排序对象但返回键
- tensorflow - 如何在 tensorflow 中读取 hive.ql.io.orc.OrcOutputFormat 表
- java - 将 PsiMethod 转换为 java.lang.reflect.Method
- vb.net - 为什么在这里设置 headerText 会退出线程,而不是抛出异常?
- c++ - C++ 添加非常大的 unsigned long 和 double
- vuejs2 - Vuejs 双向绑定数组
- ruby-on-rails - Rails 6 与 Turbolinks 和 Facebook 客户聊天
- apache-nifi - JOLT - 重新排序嵌套数组
- java - org.apache.tomcat.websocket.AsyncChannelGroupUtil 对象可能导致内存泄漏