Skip to content

Instantly share code, notes, and snippets.

@kraigspear
Created December 15, 2019 19:48
Show Gist options
  • Select an option

  • Save kraigspear/acdf5b1553eda68930dd4b6ec53d3b79 to your computer and use it in GitHub Desktop.

Select an option

Save kraigspear/acdf5b1553eda68930dd4b6ec53d3b79 to your computer and use it in GitHub Desktop.
//
// 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