完成处理程序没有被调用

completion handler not getting called

我从中学到了相当全面的方法site。我对它进行了一些定制以包含一个转义闭包,但它没有被调用,我也没有在调用者级别收到任何响应。

我在所有守卫中设置了断点,看它是否在某个级别退出,但到目前为止没有任何线索。

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([=11=] ?? "result is nil")
        print(?.name ?? "error is nil")
    }
}

Info.plist设置

在你的测试中,你会使用期望来等待闭包被调用,例如

func testGetUsers() {
    let e = expectation(description: "testGetUsers")

    userData.getUsers {
        print([=10=] ?? "result is nil")
        print(?.name ?? "error is nil")
        e.fulfill()
    }

    waitForExpectations(timeout: 10)
}

在大多数圈子中,网络请求不被视为单元测试。通常我们会“模拟”网络响应,只是测试我们的应用程序处理各种类型响应的能力。单元测试的目的不是测试与后端的集成,而是测试它如何处理各种理论响应。