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:
when(mock.myFunction(anyString())).thenAnswer(new Answer() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return (String) args[0];
}
});
Using this approach, the mock will return the same String that was passed to myFunction().
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