Cre8or
Cre8or

Reputation: 91

Testing Server Sent Events (SSE) with WebTestClient

I wanted to know what would be the best way to test SSE?

What I want to test is I want to check if message that I have sent (using Kafka) will be the same I receive in SSE.

I have read that I can do that using WebTestClient, but what I do not understand is how do I connect to SSE, send message and then check if my message is correct one.

I have provided the code below:

  public void sseIsRunning() {
    WebTestClient client = WebTestClient.bindToServer()
      .baseUrl("http://localhost:8080")
      .build();

     client.get()
      .uri("/sse/1")
      .accept(TEXT_EVENT_STREAM)
      .exchange()
      .expectStatus().isOk()
      .returnResult(MyEvent.class);

     StepVerifier.create(result.getResponseBody())
      .expectNext(myEvent())
      .thenCancel()
      .verify();
}
  private MyEvent myEvent() {
    MyEvent myEvent = new MyEvent();
    myEvent.setClientId(1);
    return myEvent;
  }
  public void messageIsSent() {
    kafka.sendMessage("myTopic", myEvent());
  }

Upvotes: 1

Views: 3713

Answers (1)

Cre8or
Cre8or

Reputation: 91

The issue in my case was that I had to subscribe

public void sseIsRunning() {
WebTestClient client = WebTestClient.bindToServer()
  .baseUrl("http://localhost:8080")
  .build();

 client.get()
  .uri("/sse/1")
  .accept(TEXT_EVENT_STREAM)
  .exchange()
  .expectStatus().isOk()
  .returnResult(MyEvent.class)
  .getResponseBody()
  .subscribe(new Consumer<String>() {
    @Override
    public void accept(String event) {
      // response map for MyEvent class
    }
  });

}

Upvotes: 1

Related Questions