Verifying Java reactive streams with StepVerifier and PublisherProbe

Reactive services rarely fail because a method returned the wrong value. More often, the problem sits between signals: an item arrives before demand, a cancellation never reaches an upstream operator, or a scheduler-dependent delay behaves differently in CI. Testing Java reactive streams therefore requires assertions about sequence, timing, backpressure, and terminal events, not just the final value.

Reactor Test provides two complementary tools for that job. StepVerifier describes what a subscriber should observe, while PublisherProbe records the protocol a publisher receives, including subscription, requests, and cancellation. Used together, they turn timing-sensitive behaviour into a deterministic contract that can be checked quickly on a developer laptop and in a shared build pipeline.

Why reactive failures need different assertions

A plain unit test often says too little about a Flux or Mono. It may pass while a downstream component requests too much, an error is replaced by completion, or a resource remains open after cancellation. These failures surface later as memory pressure, stalled consumers, or inconsistent API results, making production debugging harder than the original race.

The distinction matters in Australian teams. A Sydney-based payments service and a Melbourne-based logistics platform may both use Reactor to expose event streams, while a Brisbane team supports customers across the Asia-Pacific region during Australian business hours. Different CI queues and network latency can hide the same race, so tests need to model demand and cancellation rather than rely on a fast machine.

Time also needs careful treatment. When a test crosses midnight near the transition between Australian Eastern Standard Time and Australian Eastern Daylight Time, a wall-clock assumption can select the wrong business day. Virtual schedulers remove that local dependency, while fixed time zones such as UTC keep assertions stable. Test Detective's expert database can also help teams locate specialist knowledge when a custom operator or framework interaction is unclear.

StepVerifier makes the observable contract explicit

Both helpers live in Reactor's reactor-test module. Add the dependency through Gradle with testImplementation("io.projectreactor:reactor-test"), or use the equivalent Maven test scope. StepVerifier creates a verification chain in which each expectation consumes the next matching signal; a failed expectation reports the unexpected value, missing signal, or premature terminal state.

@Test
void emitsQueuedStateBeforeRunningState() {
    StepVerifier.create(Flux.just("queued", "running"))
            .expectSubscription()
            .expectNext("queued", "running")
            .expectComplete()
            .verify();
}

Timeouts protect a test from hanging, but real waiting is still a poor substitute for deterministic time. withVirtualTime installs a controllable scheduler, thenAwait advances it, and verifyComplete confirms the terminal signal. This is particularly useful for a delayed acknowledgement that should happen after several hours of simulated processing.

@Test
void becomesReadyAfterSimulatedDelay() {
    StepVerifier.withVirtualTime(() ->
            Mono.delay(Duration.ofHours(6))
                    .map(ignored -> "ready"))
            .thenAwait(Duration.ofHours(6))
            .expectNext("ready")
            .verifyComplete();
}

Treat the sequence as an explicit contract. expectSubscription proves that the publisher was observed, expectNext checks values in order, and expectErrorSatisfies lets the test distinguish a domain failure from cancellation. expectNoEvent can prove a value is absent for a bounded period rather than merely failing later.

StepVerifier also controls demand. Passing an initial request of zero and then calling thenRequest can reveal whether a publisher honours backpressure. Reactive concepts differ slightly between libraries, and Aaron Or Rosen's Reactive programming notes offer useful background when comparing those models.

PublisherProbe exposes demand and cancellation

PublisherProbe answers the complementary question: what did the subscriber actually send back? Wrap a publisher, exercise it through StepVerifier or another subscriber, then assert that it was subscribed, that the expected number of items was requested, and that cancellation occurred when required. It is especially valuable for operators that bridge a callback, database driver, or message broker into Reactor.

Here the initial request is deliberately zero. The test requests one item, cancels, and checks the publisher's view of those interactions:

@Test
void requestsOneItemAndCancels() {
    PublisherProbe<Integer> probe = PublisherProbe.of(Flux.never());

    StepVerifier.create(probe, 0)
            .expectSubscription()
            .thenRequest(1)
            .thenCancel()
            .verify();

    probe.assertWasSubscribed();
    probe.assertWasRequested(1);
    probe.assertWasCancelled();
}

assertWasRequested is an exact check for a fixed protocol, while assertMinRequested and assertMaxRequested are useful when the legal request count depends on the implementation. The right assertion should reflect the contract: some sources must receive exactly one signal, whereas a batching publisher may legitimately ask for a range.

PublisherProbe should usually wrap the real publisher rather than replace it with a mock. That preserves operator semantics while exposing the subscriber protocol. For an external API, keep the adapter in the test, stub only the network boundary, and confirm that cancellation propagates through retries and resource cleanup.

Comparing StepVerifier and PublisherProbe

Neither helper replaces the other. StepVerifier is strongest when the expected observable sequence and timing are the centre of the test; PublisherProbe is strongest when the request and cancellation contract is the centre. A practical Reactor test often uses StepVerifier as the subscriber and PublisherProbe as the observed publisher, because the same chain can verify values and then inspect demand.

Australian billing screens often show dates in day-first order, such as 31/03/2026, and amounts in Australian dollars. Serialising those values as strings can introduce locale assumptions that belong in a boundary test, not in an otherwise deterministic stream assertion.

Concern StepVerifier PublisherProbe Practical choice
Primary focus Emitted values, errors, completion and timing Subscription, demand and cancellation Use both for a full reactive contract
Expected sequence Fluent expectations such as expectNext Recorded subscriber interaction StepVerifier
Request control Initial request plus thenRequest Exact or bounded request assertions PublisherProbe
Cancellation Observable through thenCancel Verified with assertWasCancelled PublisherProbe
Virtual time Built in through withVirtualTime No scheduler of its own StepVerifier
Best fit Behaviour and signal-order tests Backpressure and resource-lifecycle tests Combine with the same publisher

Recommendations for a reliable reactive test suite

A reliable suite should test contracts at the level where they can fail clearly. Keep most checks as fast unit tests around operators and adapters, then add a small integration layer for actual Reactor and broker versions. This gives failures a narrow location and prevents a passing mock from hiding a wire-level incompatibility.

Test data needs local care too. If a stream contains names, account details, delivery addresses, or payment metadata, generate synthetic values rather than copied customer records. Australian teams handling personal information should also check obligations under the Privacy Act 1988 and guidance from the Office of the Australian Information Commissioner, especially when logs capture emissions for diagnosis.

Applied together, StepVerifier and PublisherProbe cover two failure modes that ordinary assertions miss. StepVerifier catches wrong or missing signals; PublisherProbe catches an incorrect subscriber conversation. That division makes failures faster to diagnose and prevents a real-time delay from masking a demand bug.

Your next concrete step is to add one test to the current service that uses StepVerifier with a virtual scheduler to reproduce its slowest asynchronous path, then repeat the test with PublisherProbe to assert the exact request and cancellation protocol.