Group Group Group Group Group Group Group Group Group

Run unit test with Combine for networking Layer

Hello ,

I would like to know how I can run a unit test for the method request in case of success without making a real request to endPoint. this the method makeRequest it’s takes as parameter URLComponent and return AnyPublisher .

  1. how I can override the dataTaskPublisher ?
import Foundation
import Combine


class MovieApi {
    private let session: URLSession
    
    init(session: URLSession = .shared) {
        self.session = session
    }
}

extension MovieApi {
    struct OpenMovieApi {
        static let scheme = "https"
        static let host = "api.themoviedb.org"
        static let path = "/3"
        static let key = "</API_KEY>"
    }
    
    enum MediaType: String, Codable {
        case all
        case movie
        case tv
        case person
    }
    
    enum TimeWindow: String, Codable {
        case day
        case week
    }
    
    func makeRequest<T>(with components: URLComponents) -> AnyPublisher<T, MovieError> where T: Decodable {
        guard let url = components.url else {
            let error = MovieError.network(description: "Couldn't Create URL")
            return Fail(error: error)
                .eraseToAnyPublisher()
        }
        
        return session
            .dataTaskPublisher(for: URLRequest(url: url))
            .mapError { error in
            .parsing(description: error.localizedDescription)
            }
            .flatMap(maxPublishers: .max(1)) { pair in
                decode(pair.data)
            }
            .eraseToAnyPublisher()
    }
}