Mockito - returning the same object as passed into method

You can use the Mockito shipped answers:

when(mock.something()).then(AdditionalAnswers.returnsFirstArg())

Where AdditionalAnswers.returnsFirstArg() could be statically imported.


It can be done easy with Java 8 lambdas:

when(mock.something(anyString())).thenAnswer(i -> i.getArguments()[0]);

You can implement an Answer and then use thenAnswer() instead.

Something similar to:

when(mock.someMethod(anyString())).thenAnswer(new Answer() {
    public Object answer(InvocationOnMock invocation) {
        return invocation.getArguments()[0];
    }
});

Of course, once you have this you can refactor the answer into a reusable answer called ReturnFirstArgument or similar.

Tags:

Java

Mockito