Pierre Henry Pierre Henry - 2 months ago 20
Java Question

Any way to avoid try/catch block for this Mockito test?

I am using Mockito to mock some objects and test my WebSocket message sender service. The send method takes a

org.springframework.web.socket.WebSocketSession
and a message, and returns a
CompletableFuture
.

In the lambda passed to the
thenAccept()
method of the
CompletableFuture
, I verify that the
session.sendMessage()
method has been called with the expected value :

WebSocketSession session = mockWebSocketSession();
TextMessage expectedMessage = new TextMessage("test text message");

sender.sendStringMessage(session, "test text message").thenAccept(nil -> {
try{ // this is what I am talking about
verify(session).sendMessage(expectedMessage);
}catch(IOException e){}
});


Since the
sendMessage()
method throws an
IOException
I am forced to add a useless try/catch block around the call on the inside the lambda. It is needlessly verbose.

How could I avoid it ?

Answer

I would rework you test in this way

final String testMessage = "test text message";
WebSocketSession session = mockWebSocketSession();

sender.sendStringMessage(session, testMessage).get(); // will wait here till operation completion

verify(session).sendMessage(new TextMessage(testMessage));

and add IOException to the test method signature.

This solution solves 2 issues:

  1. you test code is cleaner and all you assertions and verifications are at the end of your test method in one place;
  2. the solution solves race condition when you test may finish silently and green but your vitrification in CompletableFuture lambda even been executed