Last active
January 27, 2017 08:43
Testable NSURLSession using the 'Subclass and Override Method' technique.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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