我正在使用 mockito 来测试我的业务服务,它使用了一个我想模拟的实用程序。每个服务方法中至少有 2-3 次使用不同参数调用实用程序。
有没有推荐的方法使用多个 when(...).thenReturn(...)
相同的方法但不同的参数?
我也想在里面使用 any()
marcher。可能吗?
更新:示例代码。
@Test
public void myTest() {
when(service.foo(any(), new ARequest(1, "A"))).thenReturn(new AResponse(1, "passed"));
when(service.foo(any(), new ARequest(2, "2A"))).thenReturn(new AResponse(2, "passed"));
when(service.foo(any(), new BRequest(1, "B"))).thenReturn(new BResponse(112, "passed"));
c.execute();
}
public class ClassUnderTest {
Service service = new Service();
public void execute() {
AResponse ar = (AResponse) service.foo("A1", new ARequest(1, "A"));
AResponse ar2 = (AResponse) service.foo("A2", new ARequest(2, "2A"));
BResponse br = (BResponse) service.foo("B1", new BRequest(1, "B"));
}
}
public class Service {
public Object foo(String firstArgument, Object obj) {
return null; //return something
}
}
原文由 Zeeshan Bilal 发布,翻译遵循 CC BY-SA 4.0 许可协议
一种方法是避免对您的论点过于严格,以便仅通过一个
thenReturn
调用提供所有预期结果。例如,假设我想模拟这个方法:
然后,您可以通过提供任意数量的结果来模拟它,如下所示:
Calls to
foo
with any parameters will provide respectively “val1
“, ”val2
“, then any subsequent calls will provide ”val3
“ .如果您确实关心传递的值但不想依赖调用序列,您可以使用
thenAnswer
提供与第二个参数匹配的答案,就像您目前所做的那样,但有 3 个不同的thenReturn
。假设您已经覆盖了方法equals(Object o)
。或者简单地说,使用方法
anyString
和eq
作为参数游行者。假设您已经覆盖了方法equals(Object o)
。