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 step

StepVerifier.create wraps the Flux, and each expect line adds to a script of what must happen, in order. Nothing has run yet.

Step 1 of 8
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.

Which tool for which reactive test?To check what a publisher emits, use StepVerifier. If the code involves long delays, use virtual time. To drive a publisher by hand, use TestPublisher. To check that a branch was subscribed to, use PublisherProbe.Testing reactivecodeWhat it emits:StepVerifierLong delays:withVirtualTimeEmit by hand:TestPublisherWas a branch used?PublisherProbe
Which tool for which reactive test?To check what a publisher emits, use StepVerifier. If the code involves long delays, use virtual time. To drive a publisher by hand, use TestPublisher. To check that a branch was subscribed to, use PublisherProbe.Testing reactivecodeWhat it emits:StepVerifierLong delays:withVirtualTimeEmit by hand:TestPublisherWas a branch used?PublisherProbe
Which tool for which reactive test?

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();
}
Values, the end of the stream and failures
@Test
void delaysAnHour() {
    StepVerifier.withVirtualTime(() -> Mono.delay(Duration.ofHours(1)))
            .expectSubscription()
            .expectNoEvent(Duration.ofHours(1))
            .expectNext(0L)
            .verifyComplete();
}
An hour of delay, in about a millisecond
Virtual time in orderThe supplier builds the source while a fake clock is installed, so its timers use that clock. expectSubscription consumes the first event. thenAwait or expectNoEvent then moves the clock with no real wait.Supplier builds iton the fake clockexpectSubscription:the first eventthenAwait: the clockjumps forwardTimers fire,with no real waiting
Virtual time in orderThe supplier builds the source while a fake clock is installed, so its timers use that clock. expectSubscription consumes the first event. thenAwait or expectNoEvent then moves the clock with no real wait.Supplier builds iton the fake clockexpectSubscription:the first eventthenAwait: the clockjumps forwardTimers fire,with no real waiting
Virtual time in order
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();
Drive demand by hand with thenRequest

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.

  1. See what runs. With no element, the lambda never runs, so no assertion ever fails. The test checks nothing.
  2. 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.
  3. Use StepVerifier. It subscribes, waits, and fails on any unexpected signal, including an early completion.
  4. Remember verify(). Without verify(), or a method like verifyComplete(), nothing subscribes and the test passes empty. Add a timeout so a stream that never ends fails too.
  5. 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));
}
subscribe() checks nothing; StepVerifier checks every signal

How to answer

  • Without a verify call, nothing runs, and the test passes.
  • verifyComplete() is shorthand for expectComplete().verify().
  • assertNext checks an element with your own assertions, and expectNextCount skips 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 NullPointerException in 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

1. A test ends like this, with no verify call. What is the result?
StepVerifier.create(Flux.just("a"))
    .expectNext("WRONG")
    .expectComplete();
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.