2

im mocking mapper.convertValue to return 2 different return type of same class.

Target target1 = new Target();
target1.setId("123);

Target target2 = new Target();
target2.setId("345);

 Mockito.when(mapper.convertValue(anyMap(), eq(Target.class))).thenReturn(target1);
 Mockito.when(mapper.convertValue(anyMap(), eq(Target.class))).thenReturn(target2);

The actual code is called this way , where i want to mock the objectmapper to return target1 or target2 depending on the pair. Right now its overriding one over the other in order i have defined.

List<Pair<String, Target>> targetPairs = targetPairList.entrySet().stream()
                .map(pair -> ImmutablePair.of(pair.getKey(), mapper.convertValue(pair.getValue().getSourceAsMap(), Target.class)))
                .collect(Collectors.toList());

Any help is appreciated.

shdu12
  • 103
  • 3
  • 8

1 Answers1

1

You can try something like this.

Mockito.when(mapper.convertValue(anyMap(), eq(Target.class))).then(invocationOnMock -> {
  if (invocationOnMock.getArguments()[0] == givenObjectOne) {
    return target1;
  } else if (invocationOnMock.getArguments()[0] == givenObjectTwo) {
    return target2;
  }
  return null;
});

More details about Answer from Mockito can be found here. https://javadoc.io/static/org.mockito/mockito-core/3.5.2/org/mockito/stubbing/Answer.html

dhanushkac
  • 520
  • 2
  • 8
  • 25
  • Thanks for your reply . What is going to givenObjectOne or givenObjectTwo here ? As it’s going to be 2 mock objects for me depending on the pair . – shdu12 Aug 20 '20 at 07:32
  • If you need to give mocks based on the input arguments this is the way. You can also modify this to give mocks based on the invocation count – dhanushkac Aug 20 '20 at 07:45