I wan't to write a unit tests for my APIClient
. This is the method I would like to test:
typealias ResponsePublisher<T> = AnyPublisher<T, APIRequestError>
func dispatch<T: Decodable>(request: URLRequest) -> ResponsePublisher<T> {
urlSession
.dataTaskPublisher(for: request)
.receive(on: DispatchQueue.global(qos: .background))
.tryMap { data, response in
if let response: HTTPURLResponse = response as? HTTPURLResponse,
!(200...299).contains(response.statusCode) {
throw APIClient.httpError(response.statusCode)
}
return data
}
.decode(type: T.self, decoder: JSONDecoder())
.mapError { APIClient.handleNonHTTPError($0) }
.eraseToAnyPublisher()
}
What is the best solution/approach on how to properly mock a URLSession
with mocked data, response and error by overriding method from the URLSession
:
func dataTaskPublisher(for request: URLRequest) -> URLSession.DataTaskPublisher {}
which I use in dispatch
method of the APIClient
. In that case I would create an instance of a mocked URLSession
and set it as urlSession
property in my APIClient
. It just needs to return mocked (data, response and error). Also the one possible limitation is with URLSession.DataTaskPublisher
, since it is a struct
it can not be overridden, so it can not be mocked directly. Thanks for your help and suggestions.