Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.