Как пройти тест модуля загрузки изображения с помощью URLProtocol?

У меня неудачный модульный тест, в котором я создаю подкласс URLProtocol, чтобы создать его фиктивную реализацию. В конечном итоге у меня есть метод ViewModel, а именноfunc displayLogoImage(imageURL: URL, completion: @escaping (Result<UIImage, LogoError>) -> Void)что я пытаюсь проверить. Тест реализован следующим образом:

func displayLogoImage() {
   let url = URL(string: "http://d30v2pzvrfyzpo.cloudfront.net/uk/images/restaurants/114111.gif")!
   let response = HTTPURLResponse(url: url,
                                       mimeType: "image/gif",
                                       expectedContentLength: 6791,
                                       textEncodingName: "utf-8")
        
        URLProtocolMock.result = (response: response, data: Logo.json)
    
        let expectation = XCTestExpectation(description: "Logo should be downloaded")
    
        guard let imageData = try? Data(contentsOf: url) else {
            return
        }

        let image = UIImage(data: imageData)

        viewModel.displayRestauarantLogo(imageURL: urls.getLogoURL()) { result in
            switch result {
            case .success(let logo):
                XCTAssertNotNil(logo)
                expectation.fulfill()
            case .failure(_):
                XCTFail("No error should occur")
            }
        }
        wait(for: [expectation], timeout: 3)
    }

Ошибка: Ошибка асинхронного ожидания: превышено время ожидания в 3 секунды, ожидания не оправдались: "Логотип должен быть загружен". Я не вижу ничего очевидного, что неверно. Я регистрирую свой фиктивный протокол URL в тестовом классе с помощью:

override class func setUp() {
       URLProtocol.registerClass(URLProtocolMock.self)
}

Любая помощь будет оценена.

Реализация URLProtocolMock:

class TestURLProtocol: URLProtocol {
    override class func canInit(with request: URLRequest) -> Bool {
        return true
    }
    
    override class func canonicalRequest(for request: URLRequest) -> URLRequest {
        return request
    }

    static var loadingHandler: ((URLRequest) -> (HTTPURLResponse, Data?, Error?))?
    
    override func startLoading() {
        guard let handler = TestURLProtocol.loadingHandler else {
            XCTFail("Loading handler is not set.")
            return
        }

        let (response, data, error) = handler(request)

        if let data = data {
            client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
            client?.urlProtocol(self, didLoad: data)
            client?.urlProtocolDidFinishLoading(self)
        }
        else {
            client?.urlProtocol(self, didFailWithError: error!)
        }
    }
    
    override func stopLoading() {}
}

0 ответов

Другие вопросы по тегам