0

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?

1
  • 2
    "I tried something using ArgumentCaptor<String> but failed." Please show what you tried, and describe in what way it failed. Commented Jun 2, 2017 at 22:45

1 Answer 1

2

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]); }}); 
Sign up to request clarification or add additional context in comments.

1 Comment

it is missing the closing })

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.