Created
December 15, 2019 19:48
-
-
Save kraigspear/acdf5b1553eda68930dd4b6ec53d3b79 to your computer and use it in GitHub Desktop.
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
| // | |
| // URLProtocolMock.swift | |
| // WeatherKitTests | |
| // | |
| // Created by Kraig Spear on 12/15/19. | |
| // Copyright © 2019 spearware. All rights reserved. | |
| // | |
| import Foundation | |
| import XCTest | |
| class URLProtocolMock: URLProtocol { | |
| static var testUrls: [URL: Data] = [:] | |
| override class func canInit(with request: URLRequest) -> Bool { | |
| true | |
| } | |
| override class func canInit(with task: URLSessionTask) -> Bool { | |
| true | |
| } | |
| override class func canonicalRequest(for request: URLRequest) -> URLRequest { | |
| request | |
| } | |
| override func startLoading() { | |
| guard let client = self.client else { | |
| XCTFail("missing client") | |
| return | |
| } | |
| guard let url = self.request.url else { | |
| XCTFail("Request URL missing") | |
| return | |
| } | |
| guard let data = URLProtocolMock.testUrls[url] else { | |
| XCTFail("No data for URL") | |
| return | |
| } | |
| let response = HTTPURLResponse(url: url, | |
| statusCode: 200, | |
| httpVersion: nil, | |
| headerFields: nil)! | |
| client.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) | |
| client.urlProtocol(self, didLoad: data) | |
| client.urlProtocolDidFinishLoading(self) | |
| } | |
| override func stopLoading() {} | |
| } | |
| // Usage | |
| func testRadarTimesLoadedFromNetworkWhenCacheDoesNotExist() { | |
| let url = URL(string: "https://tilecache.rainviewer.com/api/maps.json")! | |
| let data = TestDataLoader.loadData(forResource: "RadarTimes") | |
| URLProtocolMock.testUrls = [url: data] | |
| let expect = expectation(description: "radarTimeLoaded") | |
| radarTimeLoadedCancel = radarTimeLoader.radarTimes.sink(receiveCompletion: { completed in | |
| switch completed { | |
| case .failure: | |
| XCTFail("Unexpected failure") | |
| case .finished: | |
| expect.fulfill() | |
| } | |
| }) { times in | |
| XCTAssertEqual(13, times.count) | |
| } | |
| XCTAssertEqual(.completed, XCTWaiter().wait(for: [expect], timeout: 1)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment