Last active
January 17, 2024 13:49
-
-
Save sssbohdan/1f8317f68f195243218e94400c46c94d to your computer and use it in GitHub Desktop.
URLProtocolMock.swift
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
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