Pierre Henry Pierre Henry - 1 month ago 8x
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

and a message, and returns a

In the lambda passed to the
method of the
, I verify that the
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
}catch(IOException e){}

Since the
method throws an
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 ?


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