|
| 1 | +#if canImport(Combine) |
| 2 | +import TestURLProtocol |
| 3 | +import XCTest |
| 4 | + |
| 5 | +final class TestURLProtocolTests: XCTestCase { |
| 6 | + private let url = URL(string: "https://www.google.com")! |
| 7 | + private var request: URLRequest { .init(url: url) } |
| 8 | + |
| 9 | + override class func setUp() { |
| 10 | + super.setUp() |
| 11 | + URLProtocol.registerClass(TestURLProtocol.self) |
| 12 | + } |
| 13 | + |
| 14 | + override class func tearDown() { |
| 15 | + super.tearDown() |
| 16 | + URLProtocol.unregisterClass(TestURLProtocol.self) |
| 17 | + } |
| 18 | + |
| 19 | + override func tearDown() { |
| 20 | + super.tearDown() |
| 21 | + TestURLProtocol.mockResponses.removeAll() |
| 22 | + } |
| 23 | + |
| 24 | + func test_canInit_withURL_withMockedResponse() { |
| 25 | + TestURLProtocol.mockResponses[url] = { _ in return (.success(Data()), nil) } |
| 26 | + XCTAssertTrue(TestURLProtocol.canInit(with: request)) |
| 27 | + } |
| 28 | + |
| 29 | + func test_cannotInit_withURL_withoutMockedResponse() { |
| 30 | + XCTAssertFalse(TestURLProtocol.canInit(with: request)) |
| 31 | + } |
| 32 | + |
| 33 | + func test_cannotInit_withMismatchingURLs_withoutMockedResponse() { |
| 34 | + let otherURL = URL(string: "https://www.two.com")! |
| 35 | + TestURLProtocol.mockResponses[url] = { _ in return (.success(Data()), nil) } |
| 36 | + XCTAssertFalse(TestURLProtocol.canInit(with: URLRequest(url: otherURL))) |
| 37 | + } |
| 38 | + |
| 39 | + func test_canonicalRequest() { |
| 40 | + XCTAssertEqual(TestURLProtocol.canonicalRequest(for: request), request) |
| 41 | + } |
| 42 | + |
| 43 | + @available(iOS 13.0, *) |
| 44 | + func test_successfulResponse() { |
| 45 | + TestURLProtocol.mockResponses[url] = { request in |
| 46 | + (result: .success(Data()), statusCode: 200) |
| 47 | + } |
| 48 | + |
| 49 | + let expectation = XCTestExpectation() |
| 50 | + let cancellable = URLSession.shared.dataTaskPublisher(for: url) |
| 51 | + .sink(receiveCompletion: { _ in }) { (data, response) in |
| 52 | + expectation.fulfill() |
| 53 | + } |
| 54 | + wait(for: [expectation], timeout: 0.2) |
| 55 | + } |
| 56 | + |
| 57 | + @available(iOS 13.0, *) |
| 58 | + func test_failedResponse() { |
| 59 | + struct TestError: Error {} |
| 60 | + TestURLProtocol.mockResponses[url] = { request in |
| 61 | + (result: .failure(TestError()), statusCode: 200) |
| 62 | + } |
| 63 | + |
| 64 | + let expectation = XCTestExpectation() |
| 65 | + let cancellable = URLSession.shared.dataTaskPublisher(for: url) |
| 66 | + .sink { completion in |
| 67 | + switch completion { |
| 68 | + case .failure: |
| 69 | + expectation.fulfill() |
| 70 | + case .finished: break |
| 71 | + } |
| 72 | + } receiveValue: { _ in |
| 73 | + } |
| 74 | + |
| 75 | + wait(for: [expectation], timeout: 0.2) |
| 76 | + } |
| 77 | +} |
| 78 | +#endif |
0 commit comments