Reputation: 39233
I'm using Mockito and would like to do something like:
Mockito.doReturn(new MyObject(capturedParameter))
. when(mockedCreatorInstance).findByParameter(anyString())
So when someone calls the method mockedCreatorInstance.findByParameter("XXXX")
, the value returned would be new MyObject("XXXX")
.
As you can see, the mocked method signature of mockedCreatorInstance
, would be
MyObject findByParameter(String parameter);
I tried something using ArgumentCaptor<String>
but failed.
What should I do to make it work?
Upvotes: 0
Views: 59
Reputation: 5062
The Mockito documentation recommends against using ArgumentCaptor<>s when stubbing rather than verifying.
I believe you can achieve what you want with an Answer:
when(mockedCreatorInstance.findByParameter(anyString()))
.thenAnswer(new Answer<MyObject>() {
public MyObject answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
return new MyObject((String) args[0]);
}});
Upvotes: 2