I am trying to test my SSE API in the way explained in the following tutorial https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#webtestclient-stream .
Unfortunately, it doesn't work for me. To generate next event it is necessary to perform some actions that will trigger it. I couldn't do it while waiting for response from WebTestClient (I didn't find the possibility to add such handler).
I found the workaround by creating separate thread that trigger generating events periodically, but it is not elegant. Is there any better way to do it?
TimerTask task = new TimerTask() {
public void run() {
while (true) {
//code that trigger generating event periodically
}
}
};
Timer timer = new Timer("Timer");
long delay = 1000L;
timer.schedule(task, delay);
FluxExchangeResult<MyEvent> result = client.get().uri("/events")
.accept(TEXT_EVENT_STREAM)
.exchange()
.expectStatus().isOk()
.returnResult(MyEvent.class);
Flux<Event> eventFlux = result.getResponseBody();
StepVerifier.create(eventFlux)
.expectNext(person)
.expectNextCount(4)
.consumeNextWith(p -> ...)
.thenCancel()
.verify();