title: How to test Server Sent Events API (written in Spring 5 Webflux), when it is necessary to perform action to generate new event?
body: <p>I am trying to test my SSE API in the way explained in the following tutorial <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#webtestclient-stream" rel="nofollow noreferrer">https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#webtestclient-stream</a> .</p>
  
  <p>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).</p>
  
  <p>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?</p>
  
  <pre><code>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&lt;MyEvent&gt; result = client.get().uri("/events")
          .accept(TEXT_EVENT_STREAM)
          .exchange()
          .expectStatus().isOk()
          .returnResult(MyEvent.class); 
  
  Flux&lt;Event&gt; eventFlux = result.getResponseBody();
  
  StepVerifier.create(eventFlux)
          .expectNext(person)
          .expectNextCount(4)
          .consumeNextWith(p -&gt; ...)
          .thenCancel()
          .verify();
  </code></pre>