目前我在我的代码中添加了依赖注入,因此可以使用模拟' 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)
一遍又一遍地重复,直到它崩溃。
答案 0 :(得分:0)
了解如何解决此问题,不得不重写Swift4的协议:
protocol URLSessionProtocol {
func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTaskProtocol
}