neves
neves

Reputation: 39233

Mockito: how to use a parameter of a mocked function?

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

Answers (1)

Andrew Shelansky
Andrew Shelansky

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

Related Questions