Testing Reactor pipelines with StepVerifier

Reactive pipelines are lazy and asynchronous, so ordinary assertions on return values do not work. The reactor-test module provides StepVerifier, which subscribes to a publisher and checks every signal in order, plus virtual time, probes and hand-driven publishers. This page explains how they work and runs each one with Reactor 3.7, including the traps that make reactive tests pass when they should fail or hang when they should finish.

Share

Contents

How reactive tests work

Calling a method that returns a Flux or Mono does not run anything, as the Reactor basics page shows, so assertEquals(expected, service.load()) compares objects that have done no work. A test has to subscribe, wait for the signals, and check them in order: every onNext value, and exactly one onComplete or onError. StepVerifier is a subscriber with a script. You describe the expected signals step by step, and a final verify... call subscribes, runs the script and waits for the end, throwing an AssertionError at the first signal that does not match. Because it is a real subscriber, it can also control demand and cancel, which ordinary code cannot.

The reactor-test toolbox
ToolPurpose
StepVerifier.create(publisher)Script the expected signals and verify them
StepVerifier.create(publisher, n), thenRequest, thenCancelTest demand and cancellation
StepVerifier.withVirtualTime(supplier)Run time-based pipelines on a virtual clock
PublisherProbeFind out whether a branch was subscribed to
TestPublisherEmit signals by hand, including ones that break the rules
StepVerifierOptionsInitial Context, scenario names, virtual time settings
verifyThenAssertThat()Check dropped elements, dropped errors and timing after the run

All examples ran with Reactor 3.7 and reactor-test 3.7 on JDK 21. They are written as main methods so their output can be shown; in a project, the same code goes into JUnit test methods, where an AssertionError is a normal test failure. For general test structure, see JUnit 5.

StepVerifier: values, completion and errors

The function under test parses strings and drops non-positive numbers, so "-1" must disappear and "x" must cause an error. The program verifies both cases, checks elements that are not simple values, and then shows the message of a failed expectation.

Java
import java.time.Duration;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;

public class StepVerifierBasics {

    static Flux<Integer> parsePositive(Flux<String> input) {
        return input.map(Integer::parseInt).filter(n -> n > 0);
    }

    public static void main(String[] args) {
        // Expect each element, then the terminal signal; verify() subscribes and waits
        Duration took = StepVerifier.create(parsePositive(Flux.just("3", "-1", "7")))
                .expectNext(3)
                .expectNext(7)
                .verifyComplete();
        System.out.println("elements and completion verified in under a second: "
                + (took.toMillis() < 1000));

        StepVerifier.create(parsePositive(Flux.just("3", "x")))
                .expectNext(3)
                .expectErrorSatisfies(e -> {
                    if (!(e instanceof NumberFormatException)) {
                        throw new AssertionError("wrong error " + e);
                    }
                })
                .verify();
        System.out.println("error after the first element verified");

        // consumeNextWith and thenConsumeWhile for checks that are not simple equality
        StepVerifier.create(Flux.range(1, 100))
                .consumeNextWith(n -> System.out.println("first element: " + n))
                .thenConsumeWhile(n -> n <= 100)
                .verifyComplete();

        // A failing expectation produces a descriptive AssertionError
        try {
            StepVerifier.create(parsePositive(Flux.just("3", "-1", "7")))
                    .expectNext(3)
                    .expectNext(-1)
                    .verifyComplete();
        } catch (AssertionError e) {
            System.out.println("failure message: " + e.getMessage());
        }
    }
}

Output:

Output
elements and completion verified in under a second: true
error after the first element verified
first element: 1
failure message: expectation "expectNext(-1)" failed (expected value: -1; actual value: 7)
  • The first verification checked the filtered values 3 and 7 and the completion signal. verify... returns how long verification took. Forgetting the terminal verify... call means nothing subscribes and nothing is checked: the test passes without testing anything. Always end the script with one.
  • expectErrorSatisfies checked the error after the element that preceded it, proving that 3 was emitted before the failure.
  • consumeNextWith ran arbitrary checks on one element, and thenConsumeWhile consumed the other 99 without listing them.
  • The failed expectation threw an AssertionError naming the step, expectNext(-1), and the actual value, 7.

The terminal methods come in pairs. verifyComplete() is short for expectComplete().verify(), and verifyError(Class), verifyErrorMessage(String) and verifyErrorMatches(predicate) do the same for errors. Each verify also has a form that takes a Duration, which matters for asynchronous publishers, as the virtual time section shows. A script must account for every signal: an unexpected extra element, or completion where an element was expected, fails the test.

Demand, cancellation and recorded elements

A real subscriber decides how much to request and when to cancel, and bugs in that area, such as a source that ignores demand or an operator that never cancels upstream, are invisible to tests that just collect a list. The program starts with zero demand, requests in steps, cancels, and checks that take really cancelled its source.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;

public class DemandAndCancel {

    public static void main(String[] args) {
        // Start with no demand, then request step by step
        List<Long> requests = new ArrayList<>();
        Flux<Integer> source = Flux.range(1, 10).doOnRequest(requests::add);
        StepVerifier.create(source, 0)
                .expectSubscription()
                .expectNoEvent(java.time.Duration.ofMillis(50))   // nothing without demand
                .thenRequest(2)
                .expectNext(1, 2)
                .thenRequest(3)
                .expectNextCount(3)
                .thenCancel()
                .verify();
        System.out.println("requests seen by the source: " + requests);

        // Was the upstream really cancelled? Useful for take(), timeouts, switchMap
        AtomicBoolean cancelled = new AtomicBoolean();
        StepVerifier.create(Flux.range(1, 1000).doOnCancel(() -> cancelled.set(true)).take(3))
                .expectNext(1, 2, 3)
                .verifyComplete();
        System.out.println("take(3) cancelled the 1,000-element source: " + cancelled.get());

        // Record elements and check them as a whole
        StepVerifier.create(Flux.just("b", "a", "c").sort())
                .recordWith(ArrayList::new)
                .expectNextCount(3)
                .consumeRecordedWith(all -> System.out.println("recorded: " + all))
                .expectRecordedMatches(all -> all.size() == 3)
                .verifyComplete();

        // expectNextCount counts without listing values
        StepVerifier.create(Flux.range(1, 500).filter(n -> n % 5 == 0))
                .expectNextCount(100)
                .verifyComplete();
        System.out.println("expectNextCount(100) passed");
    }
}

Output:

Output
requests seen by the source: [2, 3]
take(3) cancelled the 1,000-element source: true
recorded: [a, b, c]
expectNextCount(100) passed
  • StepVerifier.create(source, 0) subscribed without requesting anything, and expectNoEvent confirmed that the range emitted nothing for 50 ms. The source then saw exactly the requests the script made, 2 and then 3, and thenCancel ended the test after 5 of the 10 elements.
  • take(3) cancelled the 1,000-element source after three values, which doOnCancel recorded. The same check proves that timeouts and switchMap really stop the work they abandon.
  • recordWith collected the sorted elements so consumeRecordedWith and expectRecordedMatches could check them as a whole, useful when the order is not fixed. expectNextCount(100) checked the number of elements without listing them.

Virtual time: days in milliseconds

A pipeline that emits once a day, or retries with growing delays, cannot be tested in real time. StepVerifier.withVirtualTime installs a virtual clock in place of Reactor's time-based schedulers for the publisher it creates, and the script moves that clock with thenAwait. The program tests a daily report, an exponential backoff retry, and the mistake that makes such tests hang.

Java
import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import reactor.util.retry.Retry;

public class VirtualTime {

    // A daily report: one element every 24 hours
    static Flux<String> dailyReports() {
        return Flux.interval(Duration.ofHours(24)).map(i -> "report " + i).take(3);
    }

    public static void main(String[] args) {
        // 1. Three days pass instantly
        long t0 = System.nanoTime();
        StepVerifier.withVirtualTime(VirtualTime::dailyReports)
                .expectSubscription()
                .expectNoEvent(Duration.ofHours(24).minusSeconds(1))
                .thenAwait(Duration.ofSeconds(1))
                .expectNext("report 0")
                .thenAwait(Duration.ofDays(2))
                .expectNext("report 1", "report 2")
                .verifyComplete();
        System.out.printf("3 virtual days verified in %s%n",
                (System.nanoTime() - t0) / 1000000 < 2000 ? "under 2 real seconds" : "?");

        // 2. Retry with exponential backoff: 1 s, 2 s, 4 s between attempts
        AtomicInteger attempts = new AtomicInteger();
        StepVerifier.withVirtualTime(() -> Mono.fromCallable(() -> {
            attempts.incrementAndGet();
            throw new IllegalStateException("service down");
        }).retryWhen(Retry.backoff(3, Duration.ofSeconds(1)).jitter(0)))
                .expectSubscription()
                .thenAwait(Duration.ofSeconds(7))               // 1 + 2 + 4
                .expectErrorMessage("Retries exhausted: 3/3")
                .verify();
        System.out.println("backoff: " + attempts.get() + " attempts in 7 virtual seconds");

        // 3. The trap: a Flux built OUTSIDE the supplier uses the real clock
        Flux<String> builtTooEarly = dailyReports();
        try {
            StepVerifier.withVirtualTime(() -> builtTooEarly)
                    .thenAwait(Duration.ofDays(3))
                    .expectNextCount(3)
                    .expectComplete()
                    .verify(Duration.ofMillis(500));        // always give async tests a limit
        } catch (AssertionError e) {
            System.out.println("built outside the supplier: AssertionError: "
                    + e.getMessage().replaceAll("\\s+on reactor.*", ""));
        }
    }
}

Output:

Output
3 virtual days verified in under 2 real seconds
backoff: 4 attempts in 7 virtual seconds
built outside the supplier: AssertionError: VerifySubscriber timed out
  • expectNoEvent asserted that nothing happened for 23 hours 59 minutes 59 seconds, one more second produced the first report, and two more days the other two. Three virtual days took well under two real seconds.
  • Retry.backoff(3, 1 s) with jitter turned off waits 1, 2 and 4 seconds between attempts. After 7 virtual seconds the source had been called 4 times, the original attempt plus 3 retries, and the error said "Retries exhausted: 3/3". Testing retry delays in real time would make the test slow; testing them without time would not test them at all.
  • expectNoEvent counts the subscription itself as an event, which is why the script starts with expectSubscription(). Without it, the first expectNoEvent fails immediately.
  • The trap: the publisher must be created inside the supplier passed to withVirtualTime. builtTooEarly was created before the virtual clock existed, so its interval used the real clock and the script waited for three real days. verify(Duration.ofMillis(500)) turned that into a fast failure, "VerifySubscriber timed out". Give every asynchronous test such a limit; a plain verify() would have hung.

Probes, hand-driven publishers and Context

Some questions cannot be answered from the emitted values: whether a fallback was called at all, how an operator reacts to a source that breaks the rules, or what a pipeline reads from its Context. The program answers each one with a dedicated tool. The cache example models the common "cache first, database on a miss" pattern.

Java
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import reactor.test.StepVerifierOptions;
import reactor.test.publisher.PublisherProbe;
import reactor.test.publisher.TestPublisher;
import reactor.util.context.Context;

public class ProbesAndPublishers {

    static Mono<String> loadOrDefault(Mono<String> cache, Mono<String> database) {
        return cache.switchIfEmpty(database);
    }

    public static void main(String[] args) {
        // PublisherProbe: was the fallback branch subscribed to?
        PublisherProbe<String> db = PublisherProbe.of(Mono.just("from db"));
        StepVerifier.create(loadOrDefault(Mono.just("from cache"), db.mono()))
                .expectNext("from cache").verifyComplete();
        System.out.println("cache hit, database subscribed: " + db.wasSubscribed());
        PublisherProbe<String> db2 = PublisherProbe.of(Mono.just("from db"));
        StepVerifier.create(loadOrDefault(Mono.empty(), db2.mono()))
                .expectNext("from db").verifyComplete();
        System.out.println("cache miss, database subscribed: " + db2.wasSubscribed()
                + ", requested: " + db2.wasRequested());

        // TestPublisher: emit signals by hand, at the moment you choose
        TestPublisher<Integer> source = TestPublisher.create();
        StepVerifier.create(source.flux().map(n -> n * 10))
                .then(() -> source.emit(1, 2))
                .expectNext(10, 20)
                .verifyComplete();
        System.out.println("TestPublisher drove the pipeline by hand");
        source.assertWasSubscribed();
        source.assertNoSubscribers();
        System.out.println("assertWasSubscribed and assertNoSubscribers passed");

        // A non-compliant TestPublisher: sends more than was requested
        TestPublisher<Integer> rude = TestPublisher.createNoncompliant(
                TestPublisher.Violation.REQUEST_OVERFLOW);
        StepVerifier.create(rude.flux().take(2), 2)
                .then(() -> rude.next(1, 2, 3, 4))
                .expectNext(1, 2)
                .expectComplete()
                .verifyThenAssertThat()
                .hasDropped(3, 4);
        System.out.println("take(2) dropped the overflow values 3 and 4 after completing");

        // Context: values the subscriber provides to the whole chain
        Mono<String> greeting = Mono.deferContextual(ctx -> Mono.just("hello " + ctx.get("user")));
        StepVerifier.create(greeting, StepVerifierOptions.create()
                        .withInitialContext(Context.of("user", "ana")))
                .expectNext("hello ana").verifyComplete();
        System.out.println("context value verified");

        // expectAccessibleContext checks what the pipeline writes
        StepVerifier.create(Flux.just(1).contextWrite(Context.of("traceId", "t-1")))
                .expectAccessibleContext().contains("traceId", "t-1").then()
                .expectNext(1).verifyComplete();
        System.out.println("written context verified");
    }
}

Output:

Output
cache hit, database subscribed: false
cache miss, database subscribed: true, requested: true
TestPublisher drove the pipeline by hand
assertWasSubscribed and assertNoSubscribers passed
take(2) dropped the overflow values 3 and 4 after completing
context value verified
written context verified
  • PublisherProbe wraps a publisher and records whether it was subscribed to and requested from. On a cache hit the database branch was untouched; on a miss it was subscribed and requested. Both cases emitted a single string, so only the probe could tell them apart.
  • TestPublisher.create() emitted 1 and 2 when the script said so, and then completed. assertWasSubscribed and assertNoSubscribers checked the subscription from the publisher's side.
  • createNoncompliant(REQUEST_OVERFLOW) made a publisher that ignores demand. It sent 4 values to a subscriber that requested 2. take(2) completed after two, and verifyThenAssertThat().hasDropped(3, 4) proved that the extra values were dropped rather than delivered. Such tests matter when you write your own operators or bridge callback APIs.
  • StepVerifierOptions.withInitialContext supplied a user that the pipeline read with deferContextual, and expectAccessibleContext checked a value the pipeline wrote with contextWrite. Context is covered on the schedulers page.

Debugging a failing pipeline

When a reactive test fails with an exception, the stack trace usually shows Reactor's internal classes instead of the line of your code that built the failing step, because the step was assembled long before it ran. The program compares a plain error with one from a pipeline marked with checkpoint, and then verifies the same failure with StepVerifier.

Java
import java.util.Arrays;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;

public class Debugging {

    static Flux<Integer> parseOrders(Flux<String> lines) {
        return lines.map(String::trim)
                .map(Integer::parseInt)
                .checkpoint("parse-orders");                // a label in error traces
    }

    public static void main(String[] args) {
        // Without help, the stack trace shows Reactor internals, not your pipeline
        try {
            Flux.just("1", "x").map(Integer::parseInt).blockLast();
        } catch (NumberFormatException e) {
            long frames = e.getStackTrace().length;
            long reactorFrames = Arrays.stream(e.getStackTrace())
                    .filter(f -> f.getClassName().startsWith("reactor.")).count();
            System.out.println("plain error: " + frames + " stack frames, " + reactorFrames
                    + " of them inside reactor.*");
        }

        // checkpoint adds a suppressed exception that names the place
        try {
            parseOrders(Flux.just("10", " 20 ", "x")).blockLast();
        } catch (NumberFormatException e) {
            String trace = Arrays.stream(e.getSuppressed()).map(Throwable::toString)
                    .reduce("", String::concat);
            System.out.println("checkpoint label in the error: " + trace.contains("parse-orders"));
        }

        // In a test, StepVerifier reports which element came before the error
        StepVerifier.create(parseOrders(Flux.just("10", " 20 ", "x")))
                .expectNext(10, 20)
                .expectErrorMatches(e -> e instanceof NumberFormatException
                        && e.getMessage().contains("\"x\""))
                .verify();
        System.out.println("StepVerifier: 10 and 20 parsed, then NumberFormatException for \"x\"");
    }
}

Output:

Output
plain error: 14 stack frames, 10 of them inside reactor.*
checkpoint label in the error: true
StepVerifier: 10 and 20 parsed, then NumberFormatException for "x"
  • The plain error had 14 stack frames, 10 of them inside reactor.*, and none of them pointed at the line that created the failing map.
  • checkpoint("parse-orders") attached a suppressed exception whose text names the checkpoint, so the error report says which pipeline failed. Checkpoints are cheap and can stay in production code. Hooks.onOperatorDebug() records the assembly location of every operator, which is very helpful in tests and too slow for production.
  • StepVerifier showed exactly which elements came before the failure, 10 and 20, and expectErrorMatches checked that the error was the expected NumberFormatException for "x". .log() on a step prints every signal through it, the quickest way to see where a sequence stops.

Choosing a testing tool

Which tool answers which question
QuestionUse
Does it emit these values and complete?StepVerifier with expectNext and verifyComplete
Does it fail with the right error?expectErrorMatches, expectErrorMessage, expectErrorSatisfies
Many elements, or an unknown orderexpectNextCount, thenConsumeWhile, recordWith
Does it respect demand and cancel upstream?create(publisher, 0), thenRequest, thenCancel, doOnCancel
Delays, intervals, timeouts, retrieswithVirtualTime, building the publisher inside the supplier
Was a branch or fallback called?PublisherProbe
How does my operator handle a given sequence?TestPublisher, compliant or not
Values from the ContextStepVerifierOptions.withInitialContext, expectAccessibleContext
Any asynchronous testverify(Duration), so a bug fails fast instead of hanging
Where did it fail?checkpoint, log(), Hooks.onOperatorDebug() in tests

Keep each test focused on one pipeline and one behaviour: a script that checks values, errors, timing and Context at once is hard to read when it fails. For Spring WebFlux controllers, WebTestClient builds on these tools to test HTTP endpoints. The operators tested here are explained on the Reactor operators page.