Home >Java >javaTutorial >How to Pass Arguments Back from Mocked Methods in Java?
Returning Passed Arguments from Mocked Methods
In certain scenarios, it may be desirable for a mocked method to return the same argument that was passed to it. Mockito, a well-known mocking framework for Java, provides various approaches to achieve this behavior:
Mockito 1.9.5 with Java 8
Utilizing lambda expressions, you can now succinctly define the behavior:
<code class="java">when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);</code>
Older Mockito Versions
Alternatively, for older versions of Mockito, you can create a custom Answer:
<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>
This Answer implementation retrieves the first argument from the invocation and returns it, effectively passing back the same string that was passed to the mocked method.
The above is the detailed content of How to Pass Arguments Back from Mocked Methods in Java?. For more information, please follow other related articles on the PHP Chinese website!