【发布时间】:2019-07-16 05:54:45
【问题描述】:
我想测试 NSURLSession 但我收到错误“无法将简历发送到类 NSURLSessionDataTask 的抽象实例”。
示例代码在https://github.com/stevencurtis/abstract-instanceofclassNSURLSessionDataTask
我的 HTTP 管理器工作正常:
class HTTPManager {
static let shared: HTTPManager = HTTPManager()
private let session: URLSessionProtocol
init(session: URLSessionProtocol = URLSession.shared) {
self.session = session
}
public func get(urlString: String, completionBlock: ((Data?) -> Void)?) {
let url = URL(string: urlString)
if let usableUrl = url {
let request = URLRequest(url: usableUrl)
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
(completionBlock?(data))!
})
task.resume()
}
}
}
但是我试图模拟它
class MockURLSession: URLSessionProtocol {
func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
return URLSessionDataTask()
}
var searchedURL = URL(string: "asd")
}
然后创建测试:
func testGetRequest() {
let url = URL(string: "url")
let session = MockURLSession()
let sub = HTTPManager(session: session)
sub.get(urlString: "url", completionBlock: { [weak self] (data: Data?) -> Void in
print ("vc")
}
)
}
测试错误:resume cannot be sent to abstract instance of class NSURLSessionDataTask",我想不出解决这个错误的方法!
【问题讨论】:
-
示例代码为空
-
糟糕修复,现在在github上
-
信不信由你,这些是我正在使用的(我可以访问 Google)。我更改了语法以适应 Swift 中的更改,但我不能说问题是否在于我没有使用 typealias,而这几乎就是问题所在。
标签: swift testing mocking urlsession nsurlsessiondatatask