Video in progress
How do you test an SSE endpoint automatically when its response never ends?
I start the app with RANDOM_PORT, send a text/event-stream request with WebTestClient, take the response as a Flux, and in StepVerifier cancel the subscription once the expected events arrive. A timeout is a must, otherwise the test hangs.
📖 Answer
MockMvc is awkward here: SseEmitter works asynchronously and the response never closes, so the test waits for a result. A real server with a reactive client turns out much more natural, even if the app is Spring MVC. You add spring-boot-starter-webflux and reactor-test in test scope.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
class OrderStreamIT {
@Autowired WebTestClient client;
@Autowired OrderEvents events;
@Test
void pushesStatusChange() {
Flux<ServerSentEvent<String>> stream = client.get()
.uri("/api/orders/42/stream")
.accept(MediaType.TEXT_EVENT_STREAM)
.exchange()
.expectStatus().isOk()
.returnResult(new ParameterizedTypeReference<ServerSentEvent<String>>() {})
.getResponseBody();
StepVerifier.create(stream)
.then(() -> events.statusChanged(42, "SHIPPED"))
.expectNextMatches(e -> "order-status".equals(e.event())
&& e.data().contains("SHIPPED"))
.thenCancel()
.verify(Duration.ofSeconds(5));
}
}
There are four subtle points here:
thenCancel(): we don't wait for the stream to end; once the event we need arrives, we cut the connection ourselves. On the server side this also exercises theonCompletion/onErrorcallbacks.verify(Duration)is the timeout. Without it a wrong event name hangs the test forever.- If there are heartbeat comments, they arrive as elements too (with
datanull). Skip them withfilter(e -> e.data() != null). - The event has to be triggered after the subscription, which is exactly what
then(...)is for. If you publish first and connect afterward, the event passes by and the test fails "sometimes".
You can test reconnection (Last-Event-ID) the same way: send the request with the header set by hand and check that the missed events arrive.
Sign up to mark studied questions and save your progress.