Skip to content

Instantly share code, notes, and snippets.

@paulstringer
Last active January 27, 2017 08:43
Show Gist options
  • Save paulstringer/7f60e446c8b8b6be3647e42936b44877 to your computer and use it in GitHub Desktop.
Save paulstringer/7f60e446c8b8b6be3647e42936b44877 to your computer and use it in GitHub Desktop.
Testable NSURLSession using the 'Subclass and Override Method' technique.
class NSURLSessionTestable: NSURLSession {
var response: NSURLResponse?
var data: NSData?
override func dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask {
completionHandler(nil, self.response, nil)
return NSURLSessionDataTaskNoOp()
}
}
class NSURLSessionDataTaskNoOp: NSURLSessionDataTask {
override func resume() { }
}
/// EXAMPLE OF USAGE IN A TEST
class URLSessionHTTPClientTests: XCTestCase {
let session = NSURLSessionTestable()
var client: URLSessionHTTPClient!
override func setUp() {
super.setUp()
client = URLSessionHTTPClient(session: session)
}
func testSessionNullURLResponseClientReturnsOfflineError() {
session.response = nil
session.data = nil
client.GET("http://www.apple.com") { (URL, error) in
completedError = error
}
XCTAssertEqual(completedError, .Offline)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment