2

I'm attempting to test my own class by injecting objects that adapt the URLSession and URLSessionDataTask protocols. I'm extending NSURLSession and NSURLSessionDataTask to adopt those protocols so that I can use the existing objects normally, but use test objects in unit tests.

I have the following code, with the error commented:

typealias SessionHandler = (NSData?, NSURLResponse?, NSError?) -> Void

protocol URLSession {

  func dataTaskWithURL(url: NSURL, completionHandler: SessionHandler) -> URLSessionDataTask

}

protocol URLSessionDataTask {

}

// Type 'NSURLSession' does not conform to protocol 'URLSession'
extension NSURLSession : URLSession {}
extension NSURLSessionDataTask : URLSessionDataTask {}

I understand the error, my protocol doesn't exactly match the method as implimented by NSURLSession. How do I fix this?

kubi
  • 48,104
  • 19
  • 94
  • 118
  • No, your 'NSUrlSession' doesn't conform to your custom protocol, since you have to implement the method you defined in the protocol. – Dániel Nagy Aug 11 '15 at 18:13
  • My protocol specifies one function, which returns a `URLSessionDataTask`. `NSURLSession` has the same function, except it returns a `NSURLSessionDataTask`, which adopts `URLSessionDataTask`, so I would expect this to work. – kubi Aug 11 '15 at 18:27
  • It sounds logical, however, I think if you have this signature, you doesn't allowed to return sublcasses but the exact type. – Dániel Nagy Aug 11 '15 at 18:44

1 Answers1

0

What I ended up doing was creating a protocol extension that creates the necessary method that NSURLSession requires.

extension NSURLSession : URLSession {
  func dataTaskWithURL(url: NSURL, completionHandler: SessionHandler) -> URLSessionDataTask {
    return dataTaskWithURL(url, completionHandler: completionHandler) as NSURLSessionDataTask
  }
}
kubi
  • 48,104
  • 19
  • 94
  • 118