In object-oriented programming, mocking frameworks like Mockito are used to create a mock object that simulates the behavior of a real object for testing purposes. One common scenario in testing is the need to have a mocked method return the same argument that was passed to it.
For versions of Mockito 1.9.5 and later in conjunction with Java 8 or above, you can leverage lambda expressions to achieve this behavior:
when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);
Here, i represents an instance of InvocationOnMock, and getArguments()[0] retrieves the first argument passed to the mocked method.
For older versions of Mockito, you can use a custom Mockito Answer implementation:
<code class="java">MyInterface mock = mock(MyInterface.class); 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 custom Answer retrieves the passed argument and returns it, allowing the mocked method to echo the received input.
The above is the detailed content of How to Mock Methods to Return Arguments Received in Java?. For more information, please follow other related articles on the PHP Chinese website!