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.
Contents
How reactive tests work
Calling a method that returns a FluxMonoassertEquals(expected, service.load())onNextonCompleteonErrorStepVerifierverify...AssertionError
| Tool | Purpose |
|---|---|
StepVerifier.create(publisher) | Script the expected signals and verify them |
StepVerifier.create(publisher, n)thenRequestthenCancel | Test demand and cancellation |
StepVerifier.withVirtualTime(supplier) | Run time-based pipelines on a virtual clock |
PublisherProbe | Find out whether a branch was subscribed to |
TestPublisher | Emit signals by hand, including ones that break the rules |
StepVerifierOptions | Initial Context |
verifyThenAssertThat() | Check dropped elements, dropped errors and timing after the run |
All examples ran with Reactor 3.7 and reactor-testmainAssertionError
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.
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:
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.
returns how long verification took. Forgetting the terminalverify... call means nothing subscribes and nothing is checked: the test passes without testing anything. Always end the script with one.verify... checked the error after the element that preceded it, proving that 3 was emitted before the failure.expectErrorSatisfies ran arbitrary checks on one element, andconsumeNextWith consumed the other 99 without listing them.thenConsumeWhile- The failed expectation threw an
naming the step,AssertionError , and the actual value, 7.expectNext(-1)
The terminal methods come in pairs. verifyComplete()expectComplete().verify()verifyError(Class)verifyErrorMessage(String)verifyErrorMatches(predicate)verifyDuration
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
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:
requests seen by the source: [2, 3]
take(3) cancelled the 1,000-element source: true
recorded: [a, b, c]
expectNextCount(100) passed
subscribed without requesting anything, andStepVerifier.create(source, 0) confirmed that the range emitted nothing for 50 ms. The source then saw exactly the requests the script made, 2 and then 3, andexpectNoEvent ended the test after 5 of the 10 elements.thenCancel cancelled the 1,000-element source after three values, whichtake(3) recorded. The same check proves that timeouts anddoOnCancel really stop the work they abandon.switchMap collected the sorted elements sorecordWith andconsumeRecordedWith could check them as a whole, useful when the order is not fixed.expectRecordedMatches checked the number of elements without listing them.expectNextCount(100)
Virtual time: days in milliseconds
A pipeline that emits once a day, or retries with growing delays, cannot be tested in real time. StepVerifier.withVirtualTimethenAwait
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:
3 virtual days verified in under 2 real seconds
backoff: 4 attempts in 7 virtual seconds
built outside the supplier: AssertionError: VerifySubscriber timed out
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.expectNoEvent 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.Retry.backoff(3, 1 s) counts the subscription itself as an event, which is why the script starts withexpectNoEvent . Without it, the firstexpectSubscription() fails immediately.expectNoEvent- The trap: the publisher must be created inside the supplier passed to
.withVirtualTime was created before the virtual clock existed, so itsbuiltTooEarly used the real clock and the script waited for three real days.interval turned that into a fast failure, "VerifySubscriber timed out". Give every asynchronous test such a limit; a plainverify(Duration.ofMillis(500)) would have hung.verify()
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
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:
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
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.PublisherProbe emitted 1 and 2 when the script said so, and then completed.TestPublisher.create() andassertWasSubscribed checked the subscription from the publisher's side.assertNoSubscribers made a publisher that ignores demand. It sent 4 values to a subscriber that requested 2.createNoncompliant(REQUEST_OVERFLOW) completed after two, andtake(2) proved that the extra values were dropped rather than delivered. Such tests matter when you write your own operators or bridge callback APIs.verifyThenAssertThat().hasDropped(3, 4) supplied a user that the pipeline read withStepVerifierOptions.withInitialContext , anddeferContextual checked a value the pipeline wrote withexpectAccessibleContext . Context is covered on thecontextWriteschedulers 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 checkpointStepVerifier
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:
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
, and none of them pointed at the line that created the failingreactor.* .map 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.checkpoint("parse-orders") records the assembly location of every operator, which is very helpful in tests and too slow for production.Hooks.onOperatorDebug() showed exactly which elements came before the failure, 10 and 20, andStepVerifier checked that the error was the expectedexpectErrorMatches for "x".NumberFormatException on a step prints every signal through it, the quickest way to see where a sequence stops..log()
Choosing a testing tool
| Question | Use |
|---|---|
| Does it emit these values and complete? | StepVerifierexpectNextverifyComplete |
| Does it fail with the right error? | expectErrorMatchesexpectErrorMessageexpectErrorSatisfies |
| Many elements, or an unknown order | expectNextCountthenConsumeWhilerecordWith |
| Does it respect demand and cancel upstream? | create(publisher, 0)thenRequestthenCanceldoOnCancel |
| Delays, intervals, timeouts, retries | withVirtualTime |
| Was a branch or fallback called? | PublisherProbe |
| How does my operator handle a given sequence? | TestPublisher |
| Values from the Context | StepVerifierOptions.withInitialContextexpectAccessibleContext |
| Any asynchronous test | verify(Duration) |
| Where did it fail? | checkpointlog()Hooks.onOperatorDebug() |
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