对'URLSession'使用依赖注入会导致“BAD ACCESS”无限循环错误

问题描述 投票:0回答:1

目前我在我的代码中添加了依赖注入,因此可以使用模拟'URLSession'进行单元测试。我用这篇文章作为参考:Guide to network unit testing swift这是代码的样子(减去模拟数据):

// Protocol for MOCK/Real
protocol URLSessionProtocol {
    typealias DataTaskResult = (Data?, URLResponse?, Error?) -> Void

    func dataTask(with request: NSURLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol
}

protocol URLSessionDataTaskProtocol {
    func resume()
}

//MARK: HttpClient Implementation
class HttpClient {

    typealias completeClosure = ( _ data: Data?, _ error: Error?)->Void

    private let session: URLSessionProtocol

    init(session: URLSessionProtocol) {
        self.session = session

    }

    func get( url: URL, callback: @escaping completeClosure ) {
        let request = NSMutableURLRequest(url: url)
        request.httpMethod = "GET"
        let task = session.dataTask(with: request) { (data, response, error) in
            callback(data, error)
        }
        task.resume()
    }

}

//MARK: Conform the protocol
extension URLSession: URLSessionProtocol {
    func dataTask(with request: NSURLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol

    {
        return dataTask(with: request, completionHandler: completionHandler) as URLSessionDataTaskProtocol

    }
}

extension URLSessionDataTask: URLSessionDataTaskProtocol {}

我首先尝试使用“URLSession.shared”运行它以确保它在真实环境中运行:

let HTTP = HttpClient(session: URLSession.shared)

HTTP.get(url: URL(string: "https://sampleUrl")!) { (data, error) in}

此处出现错误“BAD ACCESS”:

extension URLSession: URLSessionProtocol {
    func dataTask(with request: NSURLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol

    {
        return dataTask(with: request, completionHandler: completionHandler) as URLSessionDataTaskProtocol//This is where the error happens

    }
}

我可以在调试导航器中看到URLSession.dataTask(with:completionHandler)一遍又一遍地重复,直到它崩溃。

ios mocking swift4 nsurlsession exc-bad-access
1个回答
0
投票

找到如何解决这个问题,不得不重写Swift4的协议:

protocol URLSessionProtocol {
    func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTaskProtocol
}
© www.soinside.com 2019 - 2024. All rights reserved.