Java Mockito 有条件地接受参数
Java Mockito when accept arguments but conditionally
我正在使用 Mockito 编写测试用例,并且必须编写对方法的期望(签名如下所示)
public Object process(Employee e);
在我的测试中class,我必须如下模拟我的期望:
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);
如何有条件地设置期望值。
您可以使用静态方法 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);
您可以使用 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());
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));
我正在使用 Mockito 编写测试用例,并且必须编写对方法的期望(签名如下所示)
public Object process(Employee e);
在我的测试中class,我必须如下模拟我的期望:
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);
如何有条件地设置期望值。
您可以使用静态方法 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);
您可以使用 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());
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));