Created
May 25, 2019 00:46
-
-
Save laevandus/a6e2748b77b4ffbd06853afea869ed97 to your computer and use it in GitHub Desktop.
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
final class WebClientTests: XCTestCase { | |
override func tearDown() { | |
TestURLProtocol.loadingHandler = nil | |
} | |
struct TestPayload: Codable, Equatable { | |
let country: String | |
} | |
func testFetchingDataSuccessfully() { | |
let expected = TestPayload(country: "Estonia") | |
let request = URLRequest(url: URL(string: "https://www.example.com")!) | |
let responseJSONData = try! JSONEncoder().encode(expected) | |
TestURLProtocol.loadingHandler = { request in | |
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)! | |
return (response, responseJSONData, nil) | |
} | |
let expectation = XCTestExpectation(description: "Loading") | |
let configuration = URLSessionConfiguration.ephemeral | |
configuration.protocolClasses = [TestURLProtocol.self] | |
let client = WebClient(urlSession: URLSession(configuration: configuration)) | |
client.fetch(request, requestDataType: TestPayload.self) { (result) in | |
switch result { | |
case .failure(let error): | |
XCTFail("Request was not successful: \(error.localizedDescription)") | |
case .success(let payload): | |
XCTAssertEqual(payload, expected) | |
} | |
expectation.fulfill() | |
} | |
wait(for: [expectation], timeout: 1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment