用不同的参数模拟相同的方法

时间:2017-01-20 15:47:16

标签: java unit-testing junit mockito

我正在使用mockito来测试我的业务服务,它使用了我想要模拟的实用程序。对于具有不同参数的实用程序,每个服务方法至少有2-3个调用。

是否有任何建议的方法为同一方法使用多个when(...).thenReturn(...)但不同的参数?

我也想在内部使用any()游行者。有可能吗?

更新:示例代码。

@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
  }
}

4 个答案:

答案 0 :(得分:23)

一种方法是避免对您的论点过于严格,以便仅通过一次thenReturn调用提供所有预期结果。

例如,让我们说我想模仿这个方法:

public String foo(String firstArgument, Object obj) {
    return "Something";
}

然后你可以通过提供你想要的结果来模拟它,如下所示:

// Mock the call of foo of any String to provide 3 results
when(mock.foo(anyString(), anyObject())).thenReturn("val1", "val2", "val3");

使用任何参数拨打foo将分别提供" val1"," val2",然后任何后续呼叫将提供" val3"

如果您关心传递的值但不想依赖于调用序列,您可以使用thenAnswer提供与第二个参数匹配的答案,就像您目前所做的那样但是有3个不同{ {1}}。

thenReturn

答案 1 :(得分:3)

正确的方法是使用eq()匹配参数,但如果您不想这样做,则只需记录多个返回值。

when(someService.doSomething(any(SomeParam.class))).thenReturn(
  firstReturnValue, secondReturnValue, thirdReturnValue
);

现在,第一个电话会返回firstValue,第二个secondValue以及所有thirdValue

答案 2 :(得分:1)

如果要模拟方法只是想验证是否传入了正确的参数,则可以使用any()并在模拟方法调用之后使用ArgumentCaptor进行验证。

答案 3 :(得分:0)

我认为:“推荐”方式将是适合您的方式;而且编程工作量最少。

您必须提供必要的规范,以使您的测试能够执行必要的操作。没有办法解决这个问题。

如果您真的关心使用的参数,那么您必须相应地指定它们。如果你不在乎;使用any()