Last active
June 9, 2021 20:52
-
-
Save harrydayexe/d28f1a9032337c15efbc31b1beec5a76 to your computer and use it in GitHub Desktop.
A URLProtocol Stub for use when unit testing URLSession
This file contains hidden or 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
/// A Stub for use with unit testing URLSession | |
class URLProtocolStub: URLProtocol { | |
// this dictionary maps URLs to test data | |
static var testURLs = [URL?: Data]() | |
static var response = HTTPURLResponse(url: "https://songlinkr.harryday.xyz", statusCode: 200, httpVersion: "HTTP/1.1", headerFields: nil) | |
// say we want to handle all types of request | |
override class func canInit(with request: URLRequest) -> Bool { | |
return true | |
} | |
// ignore this method; just send back what we were given | |
override class func canonicalRequest(for request: URLRequest) -> URLRequest { | |
return request | |
} | |
override func startLoading() { | |
// if we have a valid URL… | |
if let url = request.url { | |
// …and if we have test data for that URL… | |
if let data = URLProtocolStub.testURLs[url] { | |
self.client?.urlProtocol(self, didReceive: URLProtocolStub.response!, cacheStoragePolicy: .notAllowed) | |
// …load it immediately. | |
self.client?.urlProtocol(self, didLoad: data) | |
} | |
} | |
// mark that we've finished | |
self.client?.urlProtocolDidFinishLoading(self) | |
} | |
// this method is required but doesn't need to do anything | |
override func stopLoading() { } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Credit: https://www.hackingwithswift.com/articles/153/how-to-test-ios-networking-code-the-easy-way