What are mocking and stubbing techniques for Combine in Swift?

Mocking and stubbing techniques in Swift are crucial for testing Combine publishers. They allow developers to simulate various behaviors of publishers and subscribers without relying on real data or side effects.

Mocking Combine, Stubbing Combine, Testing in Swift, Combine Framework, Swift Unit Testing


        import Combine
        import XCTest

        class ExampleTests: XCTestCase {
            var cancellables: Set = []

            func testPublisherReturnsMockData() {
                // Mocking a publisher 
                let mockPublisher = Just("Mock Data")
                    .setFailureType(to: Error.self)
                    .eraseToAnyPublisher()

                // Subscribing to the mock publisher
                mockPublisher
                    .sink(receiveCompletion: { completion in
                        // Handle completion
                    }, receiveValue: { value in
                        // Asserting the value received is as expected
                        XCTAssertEqual(value, "Mock Data")
                    })
                    .store(in: &cancellables)
            }
            
            func testPublisherWithStubbing() {
                // Creating a stub for a network request
                let stubbedResponse = Just("Stubbed Response")
                    .setFailureType(to: Error.self)
                    .eraseToAnyPublisher()

                // Simulating a function that returns a publisher
                func fetchData() -> AnyPublisher {
                    return stubbedResponse
                }

                // Subscribing to the stubbed function
                fetchData()
                    .sink(receiveCompletion: { completion in
                        // Handle completion
                    }, receiveValue: { value in
                        // Asserting the value returned by the stubbed function is correct
                        XCTAssertEqual(value, "Stubbed Response")
                    })
                    .store(in: &cancellables)
            }
        }
    

Mocking Combine Stubbing Combine Testing in Swift Combine Framework Swift Unit Testing