我有一个函数我试图通过注入mockURLSession作为参数进行单元测试:
internal func getConnection(urlRequest: Request, mockUrlSession: MockURLSession?) {
if mockUrlSession == nil {
let dataTask = self.urlSession.dataTask(with: urlRequest as URLRequest)
dataTask.resume()
} else {
let dataTask = mockUrlSession.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
})
dataTask.resume()
}
但是当我尝试进行单元测试时,我收到了错误:
无法将“MockURLSession”类型的值转换为预期参数 输入'MockURLSession?'
这是单元测试:
func test_urlSession404(){
let mockResponse = HTTPURLResponse(url: (self.urlRequest?.url!)!, statusCode: 404, httpVersion: "HTTP/1.1", headerFields: nil)!
var mockSession = MockURLSession(mockResponse: mockResponse)
sut?.getConnection(urlRequest: self.urlRequest!, mockUrlSession: mockSession)//error here
}
即使我没有使MockURLSession参数可选,错误仍会显示减去?在MockURLSession结束时。我很困惑因为它们属于同一类型,为什么它不能转换,有没有办法让它可以注入mockURLSession?