2

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();
Dystyria
  • 63
  • 4

1 Answers1

0

I had similar issue. If I understand you correctly, you want to publish some sort of message and then check if you are getting that message or not. If that is the case then you should use subscribe and provide consumer. Here is an example.

FluxExchangeResult<MyEvent> result = client.get().uri("/events")
    .accept(TEXT_EVENT_STREAM)
    .exchange()
    .expectStatus().isOk()
    .returnResult(MyEvent.class)
    .getResponseBody()
    .subscribe(new Consumer<MyEvent>() {
        @Override
        public void accept(String event) {
        }
    });
Cre8or
  • 71
  • 1
  • 8