W3docs

Making a mocked method return an argument that was passed to it

To make a mocked method return an argument that was passed to it, you can use the Mockito.when method and pass it the argument that you want to return as the answer.

To make a mocked method return an argument that was passed to it, you can use Mockito.when combined with thenAnswer.

Here's an example:


// create mock object
MyClass mock = Mockito.mock(MyClass.class);

// define return value to be the argument passed to the method
when(mock.process(any())).thenAnswer(invocation -> invocation.getArgument(0));

// use mock in test
String result = mock.process("hello");

In this example, the process method of the mock object will return the exact argument passed to it. thenAnswer receives an InvocationOnMock object, and invocation.getArgument(0) extracts the first argument from the call.