How do I mock network layers in Combine with Swift?

In Swift, when using Combine for network requests, it's often useful to mock network layers for testing purposes. This allows you to simulate network responses and behaviors without relying on actual network calls. Here's an example of how to achieve this:

import Combine import Foundation // Network service protocol protocol NetworkService { func fetchData() -> AnyPublisher } // Real network service implementation class RealNetworkService: NetworkService { func fetchData() -> AnyPublisher { let url = URL(string: "https://api.example.com/data")! return URLSession.shared.dataTaskPublisher(for: url) .map(\.data) .eraseToAnyPublisher() } } // Mock network service implementation class MockNetworkService: NetworkService { func fetchData() -> AnyPublisher { let mockData = Data("{\"key\":\"value\"}".utf8) return Just(mockData) .setFailureType(to: Error.self) .eraseToAnyPublisher() } } // ViewModel using the NetworkService class ViewModel: ObservableObject { private var cancellables = Set() private let networkService: NetworkService @Published var data: String = "" init(networkService: NetworkService) { self.networkService = networkService fetchData() } private func fetchData() { networkService.fetchData() .decode(type: [String: String].self, decoder: JSONDecoder()) .map { $0["key"] ?? "" } .receive(on: RunLoop.main) .sink(receiveCompletion: { completion in // Handle completion }, receiveValue: { [weak self] value in self?.data = value }) .store(in: &cancellables) } }

Combine Swift Network Layer Mocking Testable Code