Sub topic 15
Testing with StepVerifier and WebTestClient
This chapter assumes you know Java lambdas and generics, can write a Spring Boot @RestController, and have read the earlier chapters on Mono, Flux, operators, annotated controllers, and error handling. You will learn two tools. StepVerifier tests a reactive pipeline on its own. WebTestClient tests an HTTP endpoint end to end.
Why reactive code needs its own test tools
A reactive pipeline does nothing until something subscribes to it. It also runs asynchronously, so a plain JUnit assertion can run before any value has arrived.
Two tempting shortcuts are both poor choices:
- Calling
block()orblockFirst()in a test works for simple cases. It hides the order of signals, it cannot check that an error arrived instead of a value, and it cannot check completion. - Calling
subscribe()and asserting afterward is racy. The test can finish before the pipeline does, and it passes without checking anything.
StepVerifier solves this. It subscribes for you, checks each signal in order, and fails the test if the sequence differs from what you declared. It also waits for the pipeline to finish.
Setting up
Both tools are in the Spring Boot test starter and Reactor's test module. With Maven, add these test-scoped dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>reactor-test provides StepVerifier. WebTestClient ships with spring-boot-starter-test and needs spring-webflux on the classpath, which your application already has.
The signals StepVerifier checks
A publisher emits three kinds of signals:
onNextcarries a value.onCompleteends the sequence normally.onErrorends the sequence with an exception.
A sequence ends with either onComplete or onError, never both. StepVerifier lets you describe the expected sequence step by step and finish with a terminal expectation.
Your first StepVerifier test
The example from the plan uppercases two strings and checks the result:
StepVerifier.create(Flux.just("a", "b").map(String::toUpperCase))
.expectNext("A", "B")
.verifyComplete();create takes the publisher. expectNext("A", "B") asserts that the next two values are A then B. verifyComplete() asserts that onComplete follows and then runs the verification. Nothing runs until a verify method is called. If you forget it, the test passes without checking anything.
Here is a complete JUnit 5 test class that tests a service method:
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
class OddSquaresTest {
Flux<Integer> oddSquares() {
return Flux.range(1, 5)
.map(n -> n * n)
.filter(n -> n % 2 == 1);
}
@Test
void emitsOddSquaresInOrder() {
StepVerifier.create(oddSquares())
.expectNext(1, 9, 25)
.verifyComplete();
}
@Test
void checksCountOnly() {
StepVerifier.create(oddSquares())
.expectNextCount(3)
.verifyComplete();
}
}Common expectations
| Method | What it checks |
|---|---|
| `expectNext(a, b)` | The next values equal the given ones, in order |
| `expectNextCount(n)` | Exactly `n` more values arrive, without checking them |
| `expectNextMatches(predicate)` | The next value satisfies a predicate |
| `assertNext(consumer)` | The next value passes your own assertions, such as AssertJ |
| `expectComplete()` | The next signal is `onComplete` |
| `expectError(Type.class)` | The next signal is an error of that type |
| `expectErrorMessage("text")` | The error has exactly this message |
| `expectErrorSatisfies(consumer)` | The error passes your own assertions |
| `verifyComplete()` | Shortcut for `expectComplete().verify()` |
| `verifyError(Type.class)` | Shortcut for `expectError(Type.class).verify()` |
| `verify()` | Runs the verification after a terminal expectation |
Use assertNext when a value is an object with several fields:
StepVerifier.create(repository.findById("42"))
.assertNext(book -> {
org.assertj.core.api.Assertions.assertThat(book.getTitle()).isEqualTo("Dune");
org.assertj.core.api.Assertions.assertThat(book.getId()).isEqualTo("42");
})
.verifyComplete();Testing errors
The chapter on error handling used onErrorResume to replace a specific error with an empty Mono. You can test both sides: the error that passes through, and the fallback that replaces it.
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
class ErrorHandlingTest {
@Test
void errorPropagates() {
Mono<String> failing = Mono.error(new IllegalStateException("boom"));
StepVerifier.create(failing)
.expectErrorMessage("boom")
.verify();
}
@Test
void fallbackReplacesError() {
Mono<String> failing = Mono.<String>error(new IllegalArgumentException("bad"))
.onErrorResume(IllegalArgumentException.class, ex -> Mono.empty());
StepVerifier.create(failing)
.verifyComplete();
}
@Test
void emptyMonoCompletesWithoutValues() {
StepVerifier.create(Mono.empty())
.expectNextCount(0)
.verifyComplete();
}
}In the second test the fallback turns the error into an empty completion, so verifyComplete() with no expectNext is the correct assertion.
Testing time without waiting
Operators such as delayElements, interval, timeout, and retryWhen with backoff depend on time. A test that really waits is slow, and a test with a tight real-time limit is flaky. StepVerifier.withVirtualTime replaces the real clock with a virtual one that you advance by hand.
There is one rule that causes most failures here. You must create the publisher inside a Supplier, so that it is built after virtual time is installed. A publisher you create before calling withVirtualTime still uses the real clock.
import java.time.Duration;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
class VirtualTimeTest {
@Test
void tickThreeTimes() {
StepVerifier.withVirtualTime(() ->
Flux.interval(Duration.ofSeconds(1)).take(3))
.expectSubscription()
.expectNoEvent(Duration.ofSeconds(1))
.expectNext(0L)
.thenAwait(Duration.ofSeconds(2))
.expectNext(1L, 2L)
.verifyComplete();
}
}expectNoEvent asserts that nothing arrives during the given virtual time, and it advances the clock by that amount. thenAwait advances the clock without that assertion. The test finishes in milliseconds even though the pipeline represents three seconds.
Verifying backpressure and cancellation
StepVerifier.create(publisher, n) requests only n values at first. Combined with thenRequest, it checks that a source respects demand, as described in the backpressure chapter.
StepVerifier.create(Flux.range(1, 10), 2)
.expectNext(1, 2)
.thenRequest(3)
.expectNext(3, 4, 5)
.thenCancel()
.verify();thenCancel() ends the test by cancelling the subscription. Use it for infinite streams such as an interval or a Server-Sent Events source. Without it, a never-ending Flux would make verify() wait forever.
Testing HTTP endpoints with WebTestClient
StepVerifier tests a pipeline. WebTestClient tests the HTTP layer: routing, status codes, headers, JSON conversion, and error mapping. It is a client built for tests, with a fluent assertion API.
There are three ways to build one, from narrowest to widest:
bindToController(...)tests one controller with no Spring context. It is fast, but filters, advice, and auto-configuration are missing.@WebFluxTeststarts a slice of the Spring context with only web components. You supply the other beans as mocks.@SpringBootTest(webEnvironment = RANDOM_PORT)starts the full application on a real port.
A slice test for the book controller
This test uses the BookController from the annotated controllers chapter. @WebFluxTest loads the controller and auto-configures a WebTestClient. @MockBean replaces the repository, so no database is needed. In Spring Boot 3.4 and later, @MockitoBean is the preferred replacement for @MockBean.
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@WebFluxTest(BookController.class)
class BookControllerTest {
@Autowired
WebTestClient client;
@MockBean
BookRepository repository;
@Test
void listReturnsAllBooks() {
when(repository.findAll()).thenReturn(
Flux.just(new Book("1", "Dune"), new Book("2", "Emma")));
client.get().uri("/books")
.exchange()
.expectStatus().isOk()
.expectBodyList(Book.class).hasSize(2);
}
@Test
void getReturnsOneBook() {
when(repository.findById("1"))
.thenReturn(Mono.just(new Book("1", "Dune")));
client.get().uri("/books/{id}", "1")
.exchange()
.expectStatus().isOk()
.expectBody(Book.class)
.value(book -> org.junit.jupiter.api.Assertions
.assertEquals("Dune", book.getTitle()));
}
@Test
void getReturns404WhenMissing() {
when(repository.findById("99")).thenReturn(Mono.empty());
client.get().uri("/books/{id}", "99")
.exchange()
.expectStatus().isNotFound();
}
}The third test covers the switchIfEmpty branch in the controller. An empty repository result becomes a ResponseStatusException, and the framework maps it to a 404. Testing that mapping at the HTTP level is the main reason to use WebTestClient instead of calling the controller method directly.
This example assumes a Book class with an (id, title) constructor and getters, and a BookRepository interface with findAll and findById. Use the types from your own project.
Testing functional endpoints
A RouterFunction can be tested without a server by binding the client to it:
WebTestClient client = WebTestClient
.bindToRouterFunction(routerFunction)
.build();Here routerFunction is the RouterFunction<ServerResponse> your configuration builds. The assertions are the same as for annotated controllers, so you can run one set of tests against both styles and confirm they behave the same.
Asserting on JSON and headers
WebTestClient can check the body structure directly with jsonPath, and it can check headers:
client.get().uri("/books/1")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBody()
.jsonPath("$.title").isEqualTo("Dune");Add import org.springframework.http.MediaType; for this snippet.
Testing a streaming endpoint
For the Server-Sent Events endpoint, returnResult gives you a Flux of the response body. You hand that Flux to StepVerifier, which combines both tools in one test:
import java.time.Duration;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.MediaType;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
Flux<Long> body = client.get().uri("/ticks")
.accept(MediaType.TEXT_EVENT_STREAM)
.exchange()
.expectStatus().isOk()
.returnResult(Long.class)
.getResponseBody();
StepVerifier.create(body)
.expectNext(0L, 1L, 2L)
.thenCancel()
.verify(Duration.ofSeconds(10));The /ticks endpoint never completes, so the test cancels after three values. Do not use expectBody() on an infinite stream, because it waits for the end of the response.
Common mistakes
- Forgetting the terminal call. Without
verify,verifyComplete, orverifyError, nothing subscribes and the test passes. Check everyStepVerifierchain. - Using
expectNexton an infinite stream withoutthenCancel. The test never ends. - Asserting inside
subscribecallbacks. An exception thrown in a callback does not fail the test reliably. UseassertNextinstead. - Creating the publisher outside
withVirtualTime. The real clock is used and the test waits in real time. - Mocking a repository method with a plain value.
when(repo.findById("1")).thenReturn(book)does not compile against aMonoreturn type, and mocking withnullcauses aNullPointerException. Always returnMono.just(...),Mono.empty(), orFlux.just(...). - Testing only the happy path. Cover empty results and errors. Those are the branches where
switchIfEmpty,onErrorResume, and status mapping live.
Exercise
A test builds Flux<Long> ticks = Flux.interval(Duration.ofSeconds(1)).take(3); and then calls StepVerifier.withVirtualTime(() -> ticks).expectNext(0L, 1L, 2L).verifyComplete();. The test takes about three real seconds, or hangs. What is wrong, and how do you fix it?
Show answer
The Flux was created before withVirtualTime, so interval uses the real clock and the virtual clock never advances it. Create the publisher inside the supplier: withVirtualTime(() -> Flux.interval(Duration.ofSeconds(1)).take(3)). Then advance virtual time, for example with .thenAwait(Duration.ofSeconds(3)) before .expectNext(0L, 1L, 2L), and finish with .verifyComplete().
Exercise
Write a WebTestClient call that checks GET /books/{id} returns status 404 when the mocked repository returns Mono.empty(). Which branch of the controller does this exercise?
Show answer
Mock the repository with when(repository.findById("99")).thenReturn(Mono.empty());, then call client.get().uri("/books/{id}", "99").exchange().expectStatus().isNotFound();. This exercises the switchIfEmpty branch, which converts the empty result into a ResponseStatusException with HttpStatus.NOT_FOUND.
Exercise
You test Flux.range(1, 10) with StepVerifier.create(flux, 2).expectNext(1, 2).thenRequest(3).expectNext(3, 4, 5).thenCancel().verify();. Why is thenCancel() used instead of verifyComplete(), and what does the initial 2 do?
Show answer
The test only receives five of the ten values, so the sequence has not completed. thenCancel() ends the test by cancelling the subscription, and verifyComplete() would fail because onComplete has not arrived. The initial 2 is the first demand the verifier signals to the publisher, so only two values flow until thenRequest(3) asks for more. This checks that the source respects backpressure.