Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write a StepVerifier test for a Flux<String> that should emit "a", "b" and then complete, and for a Mono<User> that should fail with UserNotFoundException.

For the Flux we write StepVerifier.create(flux).expectNext("a", "b").verifyComplete(), and for the Mono we write StepVerifier.create(mono).expectError(UserNotFoundException.class).verify(). A StepVerifier is only a description of expectations: nothing is subscribed and nothing is checked until verify() or one of the verifyX() shortcuts is called. For richer checks on a single item, assertNext and consumeNextWith let us run normal assertions on it.

Why this question is asked

Reactive methods return a Mono or Flux, which does nothing until something subscribes. That makes them awkward to test with plain assertions: calling the method gives us a publisher, not a result. StepVerifier, from the reactor-test module, is the standard tool for this. It subscribes, records every signal, and checks them against the expectations we wrote, in order. Interviewers ask for these two small tests because they show whether a candidate knows the API and, more importantly, the trap of a test that never verifies anything. In this answer, we will recap the signals a publisher sends, write both tests, look at richer assertions, and see what goes wrong without verify().

1A Quick Recap: Signals and Why We Need StepVerifier

A publisher sends its subscriber a sequence of signals: onSubscribe first, then zero or more onNext signals carrying items, and finally either onComplete or onError. A correct test checks the whole sequence: the right items, in the right order, and the right ending. A Flux that emits "a" and "b" and then fails is a different behaviour from one that emits them and completes, and our tests should notice the difference.

We could call block() or collectList().block() and assert on the result, but that hides the ending: an error becomes an exception thrown from block, and an infinite Flux hangs the test. StepVerifier checks signals one by one, reports exactly which expectation failed, and supports timeouts and virtual time.

2Testing a Flux That Emits Two Items and Completes

The service method under test returns Flux.just("a", "b") in this simplified example. The test describes the expected signals and then verifies.

Java
@Test
void emitsTwoLettersThenCompletes() {
Flux<String> flux = letters.first(2); // emits "a", "b", then completes
StepVerifier.create(flux)
.expectNext("a", "b") // two onNext signals, in this order
.verifyComplete(); // then onComplete; this line subscribes and checks
}
// If the Flux emitted "a", "c": fails with expectation "expectNext(b)" failed (expected value: b; actual value: c)
// If it emitted a third item "d": fails, expected onComplete but got onNext(d)

Each expectation consumes one signal. expectNext("a", "b") is shorthand for two expectNext calls. verifyComplete() expects the onComplete signal, then subscribes and runs the whole check; it also waits for the publisher to finish, so asynchronous publishers work without any sleeping in the test. The comments show why this is stricter than collecting into a list: an unexpected extra item or a missing completion fails the test.

3Testing a Mono That Fails With an Exception

Now the error case. The repository has no user with id 99, so findUser should fail with UserNotFoundException.

Java
@Test
void unknownUserFails() {
Mono<User> mono = users.findUser(99); // Mono.error(new UserNotFoundException(99))
StepVerifier.create(mono)
.expectError(UserNotFoundException.class) // expects onError with this type, and no items before it
.verify(); // subscribes and checks
}
// Stricter: also check the message
StepVerifier.create(mono)
.expectErrorMatches(e -> e instanceof UserNotFoundException
&& e.getMessage().contains("99"))
.verify(); // passes
Common StepVerifier calls
CallChecksSubscribes?
expectNext(v1, v2)next items equal v1, v2no
assertNext(consumer)runs assertions on the next itemno
expectNextCount(n)n more items, any valuesno
expectError(Type.class)terminal onError of that typeno
verify()runs all expectationsyes
verifyComplete()expects onComplete, then runsyes
verifyError(Type.class)expects onError, then runsyes

Notice that expectError is a terminal expectation, so it is followed by verify() rather than a verifyX shortcut. There is also a shortcut, verifyError(UserNotFoundException.class), which does both in one call. If the Mono emitted a User instead, the test fails with a message saying it expected an error but got onNext, which is exactly what we want to know.

4Richer Assertions on One Item

expectNext compares with equals, which is fine for strings and records but awkward for objects with generated ids or timestamps. assertNext and consumeNextWith let us run any assertions on the next item.

Java
StepVerifier.create(users.create("ana"))
.assertNext(u -> {
assertThat(u.id()).isPositive(); // generated id, value unknown in advance
assertThat(u.name()).isEqualTo("ana");
})
.verifyComplete();

If an assertion inside assertNext throws, StepVerifier reports it as the failure of that step. consumeNextWith works the same way; assertNext is the newer and more readable name. For checking many items at once there is also recordWith and consumeRecordedWith, and expectNextMatches takes a predicate.

5The Risk: Building a StepVerifier Without Calling verify()

Here is the trap. The test below compiles, runs and passes, even though the Mono fails.

Java
@Test
void looksLikeATestButChecksNothing() {
StepVerifier.create(users.findUser(99))
.expectNext(new User(99, "ghost")); // no verify(): nothing is subscribed
} // test passes, green, and tests nothing

The reason is that StepVerifier.create and the expect methods only build a script of expectations. Subscription and checking happen inside verify() or a verifyX method. Without it, the publisher is never subscribed, so no signals arrive, no expectation is compared, and JUnit sees a method that returned normally. The test is green while the code under test may be completely broken, which is worse than having no test, because it gives false confidence. Static analysis helps: IntelliJ and Error Prone-style checks can flag a StepVerifier whose result is unused, and code review should treat a StepVerifier chain that does not end in verify as a bug.

6Follow-up questions

What is the risk of a test that builds a StepVerifier but never calls verify()?

The test passes without checking anything. create and the expect methods only describe expectations; subscription and comparison happen in verify() or verifyComplete(), verifyError() and the like. Without that call the publisher is never subscribed, so even a Mono that errors or emits the wrong value produces a green test. It is a silent false positive, so we make sure every chain ends in a verify call and use static checks to catch unused StepVerifier results.

How long does verify() wait for an asynchronous publisher?

By default it waits indefinitely for the expected signals, which can hang a test if the publisher never terminates. verify(Duration.ofSeconds(5)) sets a timeout, and StepVerifier.setDefaultTimeout can set one globally. For time-based operators, virtual time is better than waiting.

Why not just call block() in tests?

block() returns the value or throws the error, which is fine for a quick check, but it cannot express that a Flux emitted exactly two items and then completed, it hangs on infinite publishers, and its failures are less precise. StepVerifier checks each signal in order and reports which expectation failed.

7Conclusion

In this answer, we tested a Flux that emits "a" and "b" and completes with StepVerifier.create(flux).expectNext("a", "b").verifyComplete(), and a Mono that fails with StepVerifier.create(mono).expectError(UserNotFoundException.class).verify(). We saw that expectations are checked signal by signal, that assertNext and consumeNextWith allow richer checks on one item, and that a StepVerifier does nothing until verify() or a verifyX() method is called, so a chain without it is a test that always passes.

What to say in the interviewAbout 80 seconds aloud

Open with

StepVerifier comes from reactor-test, and it subscribes to a publisher and checks each signal against a script of expectations. For the Flux, I write StepVerifier.create(flux), then expectNext with "a" and "b", then verifyComplete.

Then, if they want more

That checks the two items in order and that the sequence ends with onComplete, so an extra item or an error at the end would fail the test. For the Mono, I write StepVerifier.create(mono), expectError with UserNotFoundException.class, then verify, or the shortcut verifyError. If I want to check the message too, I use expectErrorMatches with a predicate.

When an item has generated values like an id, I use assertNext or consumeNextWith and run normal AssertJ assertions inside. The most important detail is that StepVerifier is lazy: create and the expect methods only build the script, and nothing is subscribed or compared until verify or one of the verify shortcuts runs.

So a test that builds a StepVerifier and forgets verify passes no matter what the code does, which is a silent false positive. I make sure every chain ends with a verify call, I like having a static analysis check for unused results, and for asynchronous publishers I pass a timeout to verify so a test cannot hang forever.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a StepVerifier test for a Flux<String> that should emit "a", "b" and then...": https://scrivio-interview-library.netlify.app/spring-boot/reactive-testing-and-ops/e75c92303d/