Skip to content

Instantly share code, notes, and snippets.

@diatrevolo
Created March 3, 2016 15:39
Show Gist options
  • Save diatrevolo/27c29796a51c2f2529fb to your computer and use it in GitHub Desktop.
Save diatrevolo/27c29796a51c2f2529fb to your computer and use it in GitHub Desktop.
import XCTest
import Alamofire
class MyRESTClientTests: XCTestCase {
var client: MyRESTClient?
var manager: Alamofire.Manager?
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.protocolClasses!.insert(MockingURLProtocol.self, atIndex: 0)
manager = Manager(configuration: configuration)
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
client = nil
super.tearDown()
}
}
class MockingURLProtocol: NSURLProtocol {
var cannedResponse: NSData?
let cannedHeaders = ["Content-Type" : "application/json; charset=utf-8"]
override func startLoading() {
let request = self.request
if request.HTTPMethod == "GET" {
if request.URL?.absoluteString == "http://notNil/items" {
cannedResponse = "{\"count\":3,\"items\":[\"car\",\"boat\",\"airplane\"]}".dataUsingEncoding(NSUTF8StringEncoding)
} else if request.URL?.absoluteString == "http://notRight/items" {
cannedResponse = "{\"count\":3,\"concepts\":[\"art\",\"beauty\",\"ennui\"]}".dataUsingEncoding(NSUTF8StringEncoding)
} else {
cannedResponse = "GARBAGE".dataUsingEncoding(NSUTF8StringEncoding)
}
let client = self.client
let response = NSHTTPURLResponse(URL: request.URL!, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: cannedHeaders)
client?.URLProtocol(self, didReceiveResponse: response!, cacheStoragePolicy: NSURLCacheStoragePolicy.NotAllowed)
client?.URLProtocol(self, didLoadData: cannedResponse!)
client?.URLProtocolDidFinishLoading(self)
}
}
override func stopLoading() {
//noop
}
override internal class func canInitWithRequest(request: NSURLRequest) -> Bool {
return request.URL?.scheme == "http" && (request.HTTPMethod == "GET")
}
override internal class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest {
return request
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment