user249117 user249117 -4 years ago 58
Java Question

How to have different return type for different parameters using Mockito?

I am using Mockito to define something like this -

when(serviceInvocation.isServiceNeeded("4105706432","AAS")).thenReturn(true);


Similar to "4105706432" , I have just 4 other string values which must have return value true.
However, for any other string , I need return type to be false.

How can this be implemented?

Answer Source

This will provide the expected behavior:

@Test
public void testMethod() {
    when(serviceInvocation.isServiceNeeded(anyString(), anyString())).thenReturn(false);
    when(serviceInvocation.isServiceNeeded("1", "AAS")).thenReturn(true);
    when(serviceInvocation.isServiceNeeded("2", "AAS")).thenReturn(true);
    when(serviceInvocation.isServiceNeeded("3", "AAS")).thenReturn(true);
    when(serviceInvocation.isServiceNeeded("4", "AAS")).thenReturn(true);
    when(serviceInvocation.isServiceNeeded("5", "AAS")).thenReturn(true);

    System.out.println(serviceInvocation.isServiceNeeded("1", "AAS"));
    System.out.println(serviceInvocation.isServiceNeeded("2", "AAS"));
    System.out.println(serviceInvocation.isServiceNeeded("3", "AAS"));
    System.out.println(serviceInvocation.isServiceNeeded("4", "AAS"));
    System.out.println(serviceInvocation.isServiceNeeded("5", "AAS"));
    System.out.println(serviceInvocation.isServiceNeeded("other1", "AAS"));
    System.out.println(serviceInvocation.isServiceNeeded("other2", "AAS"));
}

Result:

true
true
true
true
true
false
false
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download