我正在使用 Mockito 来模拟一些对象并测试我的 WebSocket 消息发送器服务。 send 方法接受一个 org.springframework.web.socket.WebSocketSession
和一个消息,并返回一个 CompletableFuture
。
在传递给 CompletableFuture
的 thenAccept()
方法的 lambda 中,我验证了 session.sendMessage()
方法已经被以期望值调用:
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){}
});
由于 sendMessage()
方法抛出一个 IOException
,我不得不在 lambda 内部的调用周围添加一个无用的 try/catch block 。这是不必要的冗长。
我该如何避免呢?
最佳答案
您可以尝试使用 Durian library
foodOnPlate.forEach(Errors.suppress().wrap(this::eat));
list.forEach(Errors.rethrow().wrap(c -> somethingThatThrows(c)));
或者自己扩展Cosumer
@FunctionalInterface
public interface ThrowingConsumer<T> extends Consumer<T> {
@Override
default void accept(final T elem) {
try {
acceptThrows(elem);
} catch (final Exception e) {
/* Do whatever here ... */
System.out.println("handling an exception...");
throw new RuntimeException(e);
}
}
void acceptThrows(T elem) throws Exception;
}
//and then pass
thenAccept((ThrowingConsumer<String>) aps -> {
// maybe some other code here...
throw new Exception("asda");
})
关于java - 有什么方法可以避免此 Mockito 测试的 try/catch block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39534069/