Quick revision
The short answer
We get a WebTestClient from @WebFluxTest or from @SpringBootTest(webEnvironment = RANDOM_PORT), request the endpoint with accept(MediaType.TEXT_EVENT_STREAM), check the status with expectStatus().isOk(), and take the body as a Flux with returnResult(Event.class).getResponseBody(). StepVerifier then asserts a bounded number of events and cancels, because the stream may never end. For delay-based logic we test the publisher directly with StepVerifier.withVirtualTime, and the same WebTestClient can test Spring MVC applications through a MockMvc binding.
What to remember
In this answer, we tested an SSE endpoint with a WebTestClient from @WebFluxTest, accepting text/event-stream, checking the 200 status, and turning the body into a Flux with returnResult().getResponseBody(). StepVerifier asserted a bounded number of events, cancelled and verified within a timeout. We tested delays with StepVerifier.withVirtualTime on the publisher, and saw that WebTestClient also binds to a real server or to MockMvc for Spring MVC applications.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We get a WebTestClient from @WebFluxTest or from @SpringBootTest(webEnvironment = RANDOM_PORT), request the endpoint with accept(MediaType.TEXT_EVENT_STREAM), check the status with expectStatus().isOk(), and take the body as a Flux with returnResult(Event.class).getResponseBody(). StepVerifier then asserts a bounded number of events and cancels, because the stream may never end. For delay-based logic we test the publisher directly with StepVerifier.withVirtualTime, and the same WebTestClient can test Spring MVC applications through a MockMvc binding.
Why this question is asked
Server-sent events, a simple HTTP format where the server keeps the response open and writes one event after another, are a common way to push updates such as order status or prices to a browser. Testing them is different from testing a normal endpoint, because the response may never complete. A test that waits for the end of the body hangs forever. Interviewers ask this to see whether we know how to assert on an infinite stream and how to deal with time. In this answer, we will look at the endpoint, write a slice test with WebTestClient and StepVerifier, handle time with virtual time, and see the other ways to bind the client.
1The Endpoint Under Test
Our controller returns a Flux, Reactor's type for a stream of 0 to many values, that emits an event every second. Producing text/event-stream tells WebFlux to write each element as a separate SSE event as soon as it is emitted.
The stream never completes on its own. That single fact shapes the whole test.
2Writing the Test With WebTestClient and StepVerifier
@WebFluxTest starts the WebFlux slice: controllers and web infrastructure, with a WebTestClient bound to them and no real server. We mock the service so the stream is predictable. StepVerifier, from reactor-test, subscribes to a publisher and checks its signals one by one.
8 messages in order. Play them, or step through them one at a time.
Cancelling ends the test cleanly even though the stream would go on forever.
Notice three details. returnResult() gives us the body as a stream instead of collecting it, which is what lets us test something that never ends. thenCancel() unsubscribes after the events we care about, the same as a browser closing the connection. And verify(Duration) puts a time limit on the whole check, so a broken stream fails the test in 5 seconds rather than hanging the build. If we need SSE fields such as id or event name, we read the body as ServerSentEvent<Event> with a ParameterizedTypeReference.
3Testing Time-Based Logic With Virtual Time
Suppose the service sends a heartbeat event if nothing happens for 30 seconds. A test that really waits 30 seconds is slow. Reactor's virtual time replaces the clock used by its schedulers, so we can move time forward instantly. It works on the publisher directly, so we use it in a unit test of the service rather than through HTTP.
The supplier lambda matters: the Flux has to be built after virtual time is installed, so operators like interval() pick up the virtual scheduler. A Flux created before the call would use the real clock and the test would wait for real.
4Full Server and MockMvc Bindings
For an end-to-end check over real HTTP, @SpringBootTest(webEnvironment = RANDOM_PORT) gives us a WebTestClient bound to the running server, and the test body stays the same. This also exercises the real Netty or servlet container's streaming behaviour, such as flushing each event.
WebTestClient is not limited to WebFlux. For a Spring MVC application that streams with SseEmitter, we can bind it to MockMvc with MockMvcWebTestClient.bindTo(mockMvc).build() and use the same fluent assertions without a server. The binding only changes how requests are executed; the assertion API stays the same.
| Setup | Server? | Good for |
|---|---|---|
@WebFluxTest | No, bound to the slice | Controller and stream shape |
@SpringBootTest RANDOM_PORT | Yes | End-to-end streaming over HTTP |
MockMvcWebTestClient.bindTo(mockMvc) | No, MockMvc | Spring MVC apps, same API |
WebTestClient.bindToServer() | Any running server | External or manual setups |
5Follow-up questions
Why not use expectBodyList(Event.class)?
expectBodyList waits for the response to complete and then decodes all of it. With an endless stream it never completes, so the test hangs. returnResult with StepVerifier consumes events as they arrive and lets us cancel.
Can I use virtual time through WebTestClient?
Not reliably, because the request passes through threads and schedulers outside the test's control. Keep virtual time for unit tests of the publisher, and in HTTP tests use short real intervals from a mocked service.
How do I check that a finite stream completes?
Use expectComplete() instead of thenCancel(). For example, a stream of exactly three events would end with expectNextCount(3).expectComplete().verify(Duration.ofSeconds(5)).
6Conclusion
In this answer, we tested an SSE endpoint with a WebTestClient from @WebFluxTest, accepting text/event-stream, checking the 200 status, and turning the body into a Flux with returnResult().getResponseBody(). StepVerifier asserted a bounded number of events, cancelled and verified within a timeout. We tested delays with StepVerifier.withVirtualTime on the publisher, and saw that WebTestClient also binds to a real server or to MockMvc for Spring MVC applications.
Open with
I would use @WebFluxTest on the controller, which gives me a WebTestClient without a server, and mock the service so the stream is predictable, for example a Flux.interval every 10 milliseconds.
Then, if they want more
Then I call get on /events with accept TEXT_EVENT_STREAM, exchange, expectStatus isOk and check the content type. The key point is not to collect the body, because an SSE stream may never finish.
So I call returnResult with Event.class and getResponseBody, which gives me a Flux, and pass it to StepVerifier: expectNext for the first event, expectNextCount for a couple more, then thenCancel, and verify with a timeout of a few seconds so a broken stream fails rather than hangs the build.
If the logic depends on time, like a heartbeat after 30 seconds, I test the service's publisher directly with StepVerifier.withVirtualTime, creating the Flux inside the supplier, and use thenAwait to jump time forward instantly. For a full end-to-end test I would use @SpringBootTest with RANDOM_PORT and the injected WebTestClient, with the same assertions.
And WebTestClient is not only for WebFlux: I can bind it to MockMvc for a Spring MVC application and keep the same fluent API.
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.
- Official documentation
- Spring Boot reference, Testing
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 "How would you test a Spring WebFlux endpoint that returns a Flux of server-sent events...": https://scrivio-interview-library.netlify.app/spring-boot/spring-boot-test/804360ecb9/