0

我正在使用 Mockito 编写测试用例,并且必须为方法编写期望(签名如下所示)

public Object process(Employee e);

在我的测试课中,我必须模拟我的期望如下:

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);

我怎样才能有条件地设定期望。

4

3 回答 3

2

您可以使用 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());
于 2018-03-08T12:24:19.623 回答
0

您可以使用静态方法,该方法Mockito.eq为您提供参数匹配器以根据您的输入指定返回值:

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);
于 2018-03-08T11:41:03.547 回答
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));
于 2018-03-08T15:02:01.043 回答