Mocking Return Values from Passed Arguments
When testing methods with specific input parameters, it can be necessary to have the mock method return the same value that was passed to it. Mockito provides several methods to achieve this, depending on the version being used.
For Mockito 1.9.5 and Java 8 :
Mockito added support for lambda expressions, allowing for direct return of the passed argument:
<code class="java">when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);</code>
For Older Mockito Versions:
Before Mockito 1.9.5, you can use Answer in the thenAnswer method:
<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>
The above is the detailed content of How to Mock Return Values Based on Input Arguments with Mockito?. For more information, please follow other related articles on the PHP Chinese website!