Skip to content

Instantly share code, notes, and snippets.

@sssbohdan
Last active January 17, 2024 13:49
Show Gist options
  • Save sssbohdan/1f8317f68f195243218e94400c46c94d to your computer and use it in GitHub Desktop.
Save sssbohdan/1f8317f68f195243218e94400c46c94d to your computer and use it in GitHub Desktop.
URLProtocolMock.swift
import Foundation
final class URLProtocolMock: URLProtocol {
static var data = [URL: (error: Error?, data: Data?)]()
override class func canInit(with request: URLRequest) -> Bool {
return true
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override func startLoading() {
guard let url = request.url, let (error, data) = URLProtocolMock.data[url] else {
fatalError("\(String(describing: request.url)) not mocked")
}
if let data {
self.client?.urlProtocol(self, didLoad: data)
} else if let error {
self.client?.urlProtocol(self, didFailWithError: error)
} else {
fatalError("Mock should contain either data or error")
}
self.client?.urlProtocolDidFinishLoading(self)
}
override func stopLoading() {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment