Home >Java >javaTutorial >How to Mock Method Returns to Echo Input Arguments in Mockito?
Mocking Method Return: Echoing Input Arguments
When testing software, it can be beneficial to have mocked methods return the arguments that are passed to them. This behavior can be particularly useful when verifying interactions or testing the flow of data through a system.
For Mockito versions 1.9.5 and above, this functionality can be achieved succinctly using lambda expressions:
when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);
In this case, the i parameter represents an InvocationOnMock instance, which provides access to the arguments passed to the mocked method.
For earlier versions of Mockito, a custom Answer is required:
<code class="java">when(mock.myFunction(anyString())).thenAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); return (String) args[0]; } });</code>
Using this approach, the mock will return the same String that was passed to myFunction().
The above is the detailed content of How to Mock Method Returns to Echo Input Arguments in Mockito?. For more information, please follow other related articles on the PHP Chinese website!