user2957954 user2957954 - 3 months ago 10
Java Question

Mockito conditions for several arguments

I'm trying to mock the results of a method. There should be two variations of the result:

Mockito.when(class.method(a,b)).thenReturn(c);



  • if
    a-b
    equals 20

  • if
    a-b
    is not 20.



How can I achieve to write two different statements and return different results?

P.S. I know how to user a condition for one argument. For example:

class MyCondition extends ArgumentMatcher<AClass> {
public boolean matches(Object sd) {
boolean toReturn = (sd instanceof AClass) && (sd >15);
return toReturn;
}
}


Mockito.when(class.method(Mockito.argThat(new MyCondition()),b)).thenAnswer(
new Answer<BClass>() {
public BClass answer(InvocationOnMock invocation) {
return new BClass();
}
});


But how can I build a condition for TWO method arguments?

Answer

Use an Answer:

Mockito.when(instance.method(Mockito.anyInt(), Mockito.anyInt()))
    .thenAnswer(
        new Answer<Integer>() {
          @Override public Integer answer(InvocationOnMock invocation) {
            int a = (Integer) invocation.getArguments()[0];
            int b = (Integer) invocation.getArguments()[1];
            if (a - b == 20) {
              return ...;
            } else {
              return ...;
            }
          }
        });