Sub topic 15
Testing with StepVerifier and WebTestClient
This chapter assumes you can write a Mono/Flux pipeline, you know the annotated controller from the earlier chapters, and you have used JUnit 5 and Mockito. You need reactor-test for StepVerifier and spring-boot-starter-test for WebTestClient. Spring Boot's WebFlux starter test setup normally pulls both in.
Why reactive code needs its own test tools
A Mono or Flux does nothing until something subscribes. A test that builds a pipeline and never subscribes tests nothing. A test that calls block() works but hides timing and signal problems. StepVerifier subscribes for you and checks each signal the publisher sends. WebTestClient does the same job one level up, for HTTP endpoints.
| Tool | Tests | Checks |
|---|---|---|
| StepVerifier | A Mono or Flux, such as a service method | Elements, errors, completion |
| WebTestClient | An HTTP endpoint | Status, headers, body |
Testing pipelines with StepVerifier
StepVerifier.create takes a publisher. You declare the expected signals in order, then call a verify method. That call subscribes and blocks until the publisher finishes, so a mismatch fails the test.
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
class PipelineTest {
@Test
void upperCasesValues() {
StepVerifier.create(Flux.just("a", "b").map(String::toUpperCase))
.expectNext("A", "B")
.verifyComplete();
}
@Test
void reportsErrors() {
Flux<Integer> failing = Flux.just(1, 2)
.concatWith(Flux.error(new IllegalStateException("boom")));
StepVerifier.create(failing)
.expectNext(1, 2)
.expectErrorMessage("boom")
.verify();
}
}Every expectation matches the next signal. verifyComplete() expects the completion signal. For a pipeline that ends in an error, use expectError or expectErrorMessage followed by verify().
Testing time-based pipelines
A Flux such as Flux.interval(Duration.ofSeconds(1)) would make a test wait in real time. StepVerifier.withVirtualTime takes a supplier and replaces the clock with a virtual one. Create the publisher inside the supplier, so it picks up the virtual scheduler. Then use thenAwait(Duration) to move time forward.
Testing endpoints with WebTestClient
WebTestClient can bind directly to a controller, so no server or Spring context is needed. The example assumes record Book(String id, String title) and a BookRepository that returns Mono and Flux.
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Mono;
class BookControllerTest {
private final BookRepository repository = mock(BookRepository.class);
private final WebTestClient client =
WebTestClient.bindToController(new BookController(repository)).build();
@Test
void returnsExistingBook() {
Book dune = new Book("1", "Dune");
when(repository.findById("1")).thenReturn(Mono.just(dune));
client.get().uri("/books/{id}", "1")
.exchange()
.expectStatus().isOk()
.expectBody(Book.class).isEqualTo(dune);
}
@Test
void returns404ForMissingBook() {
when(repository.findById("9")).thenReturn(Mono.empty());
client.get().uri("/books/{id}", "9")
.exchange()
.expectStatus().isNotFound();
}
}The second test covers the switchIfEmpty branch from the controller chapter. An empty Mono becomes a ResponseStatusException, and WebFlux turns that into a 404.
Choosing a test setup
bindToControlleris the fastest. It tests one controller with mocked collaborators.bindToRouterFunctiondoes the same for functional endpoints.@WebFluxTestloads the WebFlux slice of the Spring context, including your exception handlers and codecs.@SpringBootTestwith a running server tests the whole application.
Common mistakes
- Forgetting the
verifycall. Without it, StepVerifier never subscribes and the test passes without checking anything. - Using
block()orThread.sleepin tests. Use StepVerifier and virtual time instead. - Building a time-based publisher outside the
withVirtualTimesupplier. It then runs on the real clock.
Exercise
A test builds Flux.just(1, 2, 3).map(n -> n * 2) and calls StepVerifier.create(flux).expectNext(2, 4, 6). It always passes, even when you change the expected values to wrong ones. What is missing, and why does it pass?
Show answer
The chain has no terminal verification call, such as verifyComplete(). Without it, StepVerifier never subscribes, so the expectations are never checked. Add .verifyComplete() at the end.