这是函数,它使用Operation(NSOperation):
typealias ResultType = Result<Data>
typealias CompletionType = (ResultType) -> ()
public var onCompletion: CompletionType?
internal func getNetworkConnection(urlRequest: URLRequest, completionHandler: @escaping CompletionType) {
let task = self.urlSession.dataTask(with: urlRequest, completionHandler: { [weak self] (data, response, error) in
guard let strongSelf = self else {
return
}
if let errorResponse = error {
//strongSelf.result = Result.failure(errorResponse)
strongSelf.onCompletion?(Result.failure(errorResponse))
}
if let responseFromServer = response as? HTTPURLResponse,
200...299 ~= responseFromServer.statusCode{
if let dataResponse = data{
//strongSelf.result = Result.success(dataResponse)
strongSelf.onCompletion?(Result.success(dataResponse))//it hits this point
} else {
strongSelf.onCompletion?(Result.failure(NSError()))
}
}
strongSelf.urlSession.invalidateAndCancel()
})
task.resume()
}
我正在为它编写一个单元测试但是它似乎没有在完成块中,即使它击中了:strongSelf.onCompletion?(Result.success(dataResponse))
到目前为止,这是单元测试的样子:
func test_getNetworkConnection(){
let promise = expectation(description: "Completion handler invoked")
sut?.getNetworkConnection(urlRequest: URLRequest(url: requestURL), completionHandler: { (data) in
print(data) //never prints
promise.fulfill()
})
wait(for: [promise], timeout: 100, enforceOrder: true)//exaggerated timeout but it fails
// XCTAssertTrue(returnedResponse!)
}
知道可能是什么问题吗?
答案 0 :(得分:1)
你有一些问题。
strongSelf.onCompletion?...
,但onCompletion
为nil
,因此它无法执行任何操作。getNetworkConnection
函数有一个永不使用的completionHandler
参数。getNetworkConnection
的来电取决于被调用的completionHandler
。 onCompletion
属性似乎没有意义。
在数据任务中,通过调用strongSelf.onCompletion?...
参数替换对completionHandler
的调用。
typealias ResultType = Result<Data>
typealias CompletionType = (ResultType) -> ()
internal func getNetworkConnection(urlRequest: URLRequest, completionHandler: @escaping CompletionType) {
let task = self.urlSession.dataTask(with: urlRequest, completionHandler: { [weak self] (data, response, error) in
guard let strongSelf = self else {
return
}
if let errorResponse = error {
completionHandler(Result.failure(errorResponse))
}
if let responseFromServer = response as? HTTPURLResponse,
200...299 ~= responseFromServer.statusCode{
if let dataResponse = data{
completionHandler(Result.success(dataResponse))
} else {
completionHandler(Result.failure(NSError()))
}
} else {
// TODO - need to call completionHandler here too
}
strongSelf.urlSession.invalidateAndCancel()
})
task.resume()
}