Mockito : how to mock method return value based on argument ?

When using mockito to mock some methods behaviour, you may want to change your mocked method return value based on an argument value.

This is not obvious, but quite simple to achieve, thanks to this SO post. The following example show how to mock a call to the myMethod() function by returning the first string parameter.

when(mockObject.myMethod(anyString()))
     .thenAnswer(invocation -> invocation.getArgument(0, String.class));

Leave a Reply

Your email address will not be published.