How do I test Combine pipelines with Combine in Swift?

Testing Combine pipelines in Swift can be done by creating test cases that simulate different scenarios and verify the behavior of your publishers and subscribers. This involves using the XCTest framework alongside Combine's testing capabilities.

Combine, Swift, testing, Combine pipelines, XCTest

This guide provides an overview of how to test Combine pipelines in Swift using the XCTest framework to ensure your Combine code behaves as expected.

import XCTest
import Combine

struct User {
    let name: String
}

class UserService {
    func fetchUser() -> AnyPublisher {
        Just(User(name: "John Doe"))
            .delay(for: .seconds(1), scheduler: RunLoop.main)
            .eraseToAnyPublisher()
    }
}

class UserServiceTests: XCTestCase {
    var cancellables = Set()
    
    func testFetchUser() {
        let expectation = XCTestExpectation(description: "Fetch User")
        
        let userService = UserService()
        
        userService.fetchUser()
            .sink(receiveValue: { user in
                XCTAssertEqual(user.name, "John Doe")
                expectation.fulfill()
            })
            .store(in: &cancellables)
        
        wait(for: [expectation], timeout: 2.0)
    }
}
        

Combine Swift testing Combine pipelines XCTest