MockURLProtocol.swift 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. //
  2. // MockURLProtocol.swift
  3. // LiveLikeGiphyChallenge
  4. //
  5. // Created by Irina Smokvarska on 2/1/22.
  6. //
  7. import XCTest
  8. @testable import LiveLikeGiphyChallenge
  9. //MARK: MockURLProtocol
  10. class MockURLProtocol: URLProtocol {
  11. static var requestHandler: ((URLRequest) throws -> (HTTPURLResponse, Data))?
  12. override class func canInit(with request: URLRequest) -> Bool {
  13. return true
  14. }
  15. override class func canonicalRequest(for request: URLRequest) -> URLRequest {
  16. return request
  17. }
  18. override func startLoading() {
  19. guard let handler = MockURLProtocol.requestHandler else {
  20. XCTFail("Received unexpected request with no handler set")
  21. return
  22. }
  23. do {
  24. let (response, data) = try handler(request)
  25. client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
  26. client?.urlProtocol(self, didLoad: data)
  27. client?.urlProtocolDidFinishLoading(self)
  28. } catch {
  29. client?.urlProtocol(self, didFailWithError: error)
  30. }
  31. }
  32. override func stopLoading() {
  33. }
  34. }