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

Zee*_*lal 25 java junit unit-testing 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
  }
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*tto 32

一种方法是避免对你的论点过于严格,以便只用一次thenReturn调用就能提供所有预期的结果.

例如,假设我想模拟这个方法:

public String foo(String firstArgument, Object obj) {
    return "Something";
}
Run Code Online (Sandbox Code Playgroud)

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

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

foo任何参数的调用将分别提供" val1"," val2",然后任何后续调用将提供" val3".


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

when(mock.foo(anyString(), anyObject())).thenAnswer(
    invocation -> {
        Object argument = invocation.getArguments()[1];
        if (argument.equals(new ARequest(1, "A"))) {
            return new AResponse(1, "passed");
        } else if (argument.equals(new ARequest(2, "2A"))) {
            return new AResponse(2, "passed");
        } else if (argument.equals(new BRequest(1, "B"))) {
            return new BResponse(112, "passed");
        }
        throw new InvalidUseOfMatchersException(
            String.format("Argument %s does not match", argument)
        );
    }
);
Run Code Online (Sandbox Code Playgroud)


Sea*_*oyd 7

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

when(someService.doSomething(any(SomeParam.class))).thenReturn(
  firstReturnValue, secondReturnValue, thirdReturnValue
);
Run Code Online (Sandbox Code Playgroud)

现在第一个调用将返回firstValue,第二个secondValue和所有后续调用将返回thirdValue