[英]Java Mockito when accept arguments but conditionally
I am writing a test case using Mockito, and have to write expectation for a method (signature shown below) 我正在使用Mockito编写测试用例,并且必须编写对方法的期望(如下所示的签名)
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. 我如何有条件地设定期望。
You can do it using Mockito Answer 您可以使用Mockito回答
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());
You case use the static method Mockito.eq
which provides you with an argument matcher to specify returned values based on your input: 您可以使用静态方法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.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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.