Testing reactive code
Mid-level Differentiator 3 min
On this page
The question
How do you test a Flux, and what does StepVerifier do?
30-second answer
Use StepVerifier from reactor-test. You script what should happen: expectNext for values, expectError for failures, and expectComplete for the end. verify() subscribes and checks each real signal against the next line, in order, blocking the test until it finishes. It tests order and the terminal signal, which a block() on a list cannot show.
Understand it
StepVerifier consumes a script of expectations
Step by stepStepVerifier.create wraps the Flux, and each expect line adds to a script of what must happen, in order. Nothing has run yet.
View as text
The test code is drawn line by line, with a mark on each line when it is waiting, met or failed. A line below names the real signal that just arrived from the Flux, which emits a, then b, then completes.
StepVerifier.create wraps the Flux, and each expect line adds to a script of what must happen, in order. Nothing has run yet.
verify() is what subscribes. It runs the script against the real signals, and blocks the test until the script ends. Without it, nothing runs and the test passes.
The Flux emits "a", and the first expectation consumes it: it matches.
The Flux emits "b", and the next expectation consumes it: it matches too.
onComplete matches expectComplete. The script is finished, so the test passes.
A wrong value fails at once and names both sides: expected value: x; actual value: b. A real signal must match the next line of the script.
The most common mistake: leave out verify() and a wrong expectation still passes, because nothing subscribed. Any chain ending in expectComplete needs verify.
withVirtualTime swaps in a fake clock, so thenAwait(1 hour) takes about a millisecond. Build the source inside the supplier, or it uses the real clock and hangs.
The test code is drawn line by line, with a mark on each line when it is waiting, met or failed. A line below names the real signal that just arrived from the Flux, which emits a, then b, then completes.
StepVerifier.create wraps the Flux, and each expect line adds to a script of what must happen, in order. Nothing has run yet.
verify() is what subscribes. It runs the script against the real signals, and blocks the test until the script ends. Without it, nothing runs and the test passes.
The Flux emits "a", and the first expectation consumes it: it matches.
The Flux emits "b", and the next expectation consumes it: it matches too.
onComplete matches expectComplete. The script is finished, so the test passes.
A wrong value fails at once and names both sides: expected value: x; actual value: b. A real signal must match the next line of the script.
The most common mistake: leave out verify() and a wrong expectation still passes, because nothing subscribed. Any chain ending in expectComplete needs verify.
withVirtualTime swaps in a fake clock, so thenAwait(1 hour) takes about a millisecond. Build the source inside the supplier, or it uses the real clock and hangs.
Takeaway: StepVerifier subscribes when you call verify, then matches each real signal against the next line of your script, including how the stream ends. Virtual time removes real waits.
In code
@Test
void emitsThenCompletes() {
StepVerifier.create(Flux.just("a", "b"))
.expectNext("a", "b")
.verifyComplete();
}
@Test
void failsWithAMessage() {
StepVerifier.create(Mono.error(new IllegalStateException("boom")))
.verifyErrorMessage("boom");
}
@Test
void checksDemand() {
StepVerifier.create(Flux.range(1, 3), 1) // request only 1
.expectNext(1)
.thenRequest(2)
.expectNext(2, 3)
.verifyComplete();
}@Test
void delaysAnHour() {
StepVerifier.withVirtualTime(() -> Mono.delay(Duration.ofHours(1)))
.expectSubscription()
.expectNoEvent(Duration.ofHours(1))
.expectNext(0L)
.verifyComplete();
}StepVerifier.create(Flux.range(1, 10), 2) // the first request is for 2 elements
.expectNext(1, 2)
.thenRequest(3)
.expectNext(3, 4, 5)
.thenCancel()
.verify();Solve it
A test stays green although the code emits nothing
priceService.prices() broke and now returns an empty Flux. Its test still passes. The test calls
prices().subscribe(p -> assertTrue(p.amount() > 0)). Explain why and rewrite it.
- See what runs. With no element, the lambda never runs, so no assertion ever fails. The test checks nothing.
- See what else is lost. With asynchronous code, the method can return before any element arrives, and an assertion error on another thread does not fail the test.
- Use
StepVerifier. It subscribes, waits, and fails on any unexpected signal, including an early completion. - Remember
verify(). Withoutverify(), or a method likeverifyComplete(), nothing subscribes and the test passes empty. Add a timeout so a stream that never ends fails too. - Check. Break the code on purpose so it emits nothing: the new test fails.
@Test
void pricesArePositiveBroken() {
Wrong priceService.prices().subscribe(p -> assertTrue(p.amount() > 0)); // empty Flux: green
}
@Test
void pricesArePositive() {
Right StepVerifier.create(priceService.prices())
Right .expectNextMatches(p -> p.amount() > 0) // at least one price, or the test fails
Right .thenConsumeWhile(p -> p.amount() > 0)
Right .expectComplete()
Right .verify(Duration.ofSeconds(5));
}How to answer
- Without a
verifycall, nothing runs, and the test passes. verifyComplete()is shorthand forexpectComplete().verify().assertNextchecks an element with your own assertions, andexpectNextCountskips many.- Pass a timeout to
verify(Duration)so that a stuck stream fails instead of hanging.
Common mistakes
- Forgetting
verify(), so that a wrong expectation still passes. - Testing with
block()alone, which hides ordering, demand and how the stream ended.
Follow-up questions
How do you control a publisher in a test, or check that a fallback was actually used?
TestPublisher lets you emit by hand, so you can trigger exact sequences, and even misbehave on purpose. PublisherProbe wraps a publisher and records what happened to it, so assertWasSubscribed proves a switchIfEmpty branch ran. With Mockito, return a Mono from a stub, and a test can then use StepVerifier on the result as usual.
- A probe answers "was this branch used?", which output alone may not show.
- Stubbing a Mono method to return null gives a
NullPointerExceptionin the chain.
See it in the infographic: StepVerifier consumes a script of expectations
How do you test code that waits for an hour? What is virtual time?
StepVerifier.withVirtualTime(() -> source) installs a fake clock in place of Reactor's default schedulers. thenAwait(Duration.ofHours(1)) then moves it forward at once, so the test takes about a millisecond. Build the source inside the supplier: built outside, it keeps the real clock, and the test times out.
Why does expectNoEvent fail right at the start of a virtual-time test?
Because subscribing is itself an event, so expectNoEvent immediately sees onSubscribe and fails. Put expectSubscription() before it, which consumes that event, and expectNoEvent then checks the quiet period you meant to test.
Check yourself
Show answers
- The test passes, and nothing ran.: Correct. expectComplete only builds the script. Only verify subscribes, and a subscription count of 0 was measured.
- The test fails on "WRONG".: Incorrect. It would, with verify(). Without it, the script never runs.
- The test hangs.: Incorrect. Nothing waits, because nothing was subscribed.