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:
MyInterface mock = mock(MyInterface.class);
when(mock.myFunction(anyString())).thenAnswer(new Answer() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return (String) args[0];
}
});
This custom Answer retrieves the passed argument and returns it, allowing the mocked method to echo the received input.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3