我正在对completionHandler抛出错误的情况进行单元测试。但我不确定如何提出这个错误。
class MockErrorSession: URLSessionProtocol {
var nextDataTask = MockURLSessionDataTask()
var nextData: Data?
var nextError: Error?
func dataTask(with request: NSURLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol {
nextError = ?
completionHandler(nextData, successHttpURLResponse(request: request), nextError)
return nextDataTask as URLSessionDataTaskProtocol
}
}
我需要以某种方式填充nextError
我试着这样做,
enum MyError : Error {
case RuntimeError(String)
}
func throwError(_ message: String) throws {
throw MyError.RuntimeError(message)
}
nextError = try throwError("test") as! Error
请问任何建议?
答案 0 :(得分:0)
您的函数dataTask(with:completionHandler:)
似乎没有标记为throws
/ rethrows
,在这种情况下,似乎错误只是传递给完成块。
既然函数也没有关闭" throws
",你可以throw
错误&因此,无论如何,您以后都无法do
- try
- catch
。
根据我的假设,只需以下内容即可:
nextError = MyError.RuntimeError("test")
即
enum MyError : Error {
case RuntimeError(String)
}
func dataTask(with request: NSURLRequest,
completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol {
nextError = MyError.RuntimeError("test")
completionHandler(nextData,
successHttpURLResponse(request: request),
nextError)
return nextDataTask as URLSessionDataTaskProtocol
}