Home > Blockchain >  How to use lambda expression in doAnswer interface
How to use lambda expression in doAnswer interface

Time:04-25

List list = new LinkedList();


List spy = spy(list);

doAnswer(invocation -> "java").when(spy).get(0);

assertEquals("java", spy.get(0));

Could you please explain what does mean by (invocation -> "java") ? I do not Understand this Expression.

CodePudding user response:

doAnwer requires an Answer. This is an interface with only one method:

T answer​(InvocationOnMock invocation)

Because there's only one method, it can be used as a lambda. Your invocation -> "java" can be written as an anonymous inner class:

doAnswer(new Answer<String>() {
    String anwer(InvocationOnMock invocation) {
        return "java";
    }
})

So in other words: the invocation part is the InvocationOnMock argument, and the "java" part is the return value.

  • Related