evolution
evolution

Reputation: 4722

Mockito control output returned based off input

I have issue where when I use Java parallelStream instead of stream my tests fail. This happens because I am returning Mock objects in a strict order rather than controlling Mock objects returned based on input.

The following is my current code used to return mocks objects:

when(myOperation.getSomething(any(String.class)))
    .thenAnswer(AdditionalAnswers.returnsElementsOf(aListOfThings)));

How can I concisely control the return value based off the argument I am passing to "getSomething"?

Upvotes: 2

Views: 1018

Answers (2)

Jeff Bowman
Jeff Bowman

Reputation: 95634

Instead of using an Answer, you can just iterate across your values and set up specific stubs for each one. Unlike with an Answer, you have to be able to predict all values for which you're stubbed, but for your particular case here it sounds like that might not be a problem.

for (int i = 0; i < aListOfThings.size(); i++) {
  when(myOperation.getSomething(aListOfKeys.get(i)))
      .thenReturn(aListOfThings.get(i));
}

Upvotes: 2

user180100
user180100

Reputation:

You can do something like that:

when(myOperation.getSomething(any(String.class))).thenAnswer(new Answer<SomeThing>() {
    @Override
    public SomeThing answer(final InvocationOnMock invocation) throws Throwable {
        // HERE ====> use invocation.getArguments()
        return new SomeThing();
    }
});

Here the answer return a SomeThing instance, you will need to adjust to your needs

Some reading:

Upvotes: 4

Related Questions