1

I am writing a test case using Mockito, and have to write expectation for a method (signature shown below)

public Object process(Employee e);

In my test class, I have to simulate my expectations as follows:

when(someClass.process("any Employee with id between 1 and 100.").thenReturn(object1);
when(someClass.process("any Employee with id between 101 and 200.").thenReturn(object2);

How can I set expectations conditionally.

pankaj_ar
  • 757
  • 2
  • 10
  • 33

3 Answers3

3

You can do it using Mockito Answer

final ArgumentCaptor<Employee> employeeCaptor = ArgumentCaptor.forClass(Employee.class);

Mockito.doAnswer(invocation -> {
    Employee employee = employeeCaptor.getValue();
    if(employee.getId() > 1 && employee.getId() < 100)
      return object1;
    else if(employee.getId() > 101 && employee.getId() < 200)
      return object2;
    else someOtherObject;
}).when(someClass).process(employeeCaptor.capture());
pvpkiran
  • 25,582
  • 8
  • 87
  • 134
0

You case use the static method Mockito.eq which provides you with an argument matcher to specify returned values based on your input:

when(someClass.process(Mockito.eq("any Employee with id between 1 and 100.")).thenReturn(object1);
when(someClass.process(Mockito.eq("any Employee with id between 101 and 200.")).thenReturn(object2);
Alexandre Dupriez
  • 3,026
  • 20
  • 25
0
Mockito.doAnswer((invocation) -> {
            Employee argument = (Employee) invocation.getArguments()[0];
            int id = argument.getId();
            if (id >= 1 && id <= 100) {
                return object1;
            } else if (id >= 101 && id <= 200) {
                return object2;
            }
            return null; 
        }).when(someClass).process(Matchers.any(Employee.class));
Chamly Idunil
  • 1,848
  • 1
  • 18
  • 33