How CombineExpectations works
masterCombineExpectations streamlines testing Combine publishers by reducing the boilerplate required when using XCTestExpectation.
Core Workflow
- Record: Call
.record()on a publisher to create arecorderobject. - Wait or Get: Use
wait(for:timeout:description:)to asynchronously wait for a specific state (like elements being emitted or the publisher finishing), or use.get()for synchronous retrieval if the expectation is already met. - Assert: Use standard
XCTAssertmethods on the returned values.
Behavior Rules
- Timeouts: The test fails if an expectation is not fulfilled within the specified
timeout. - Errors: If a publisher completes with a failure, the
waitmethod throws that publisher error. - Immediate Return: The
waitmethod returns immediately if the expectation has already reached the desired state. - Multiple Waits: You can call
waitmultiple times on the same recorder to step through a publisher's lifecycle (e.g., waiting for the first element, then the second, then completion).
import XCTest
import CombineExpectations
class PublisherTests: XCTestCase {
func testElements() throws {
let publisher = ...
let recorder = publisher.record()
// Wait for a publisher expectation
let elements = try wait(for: recorder.elements, timeout: ..., description: "Elements")
XCTAssertEqual(elements, ["Hello", "World!"])
}
}