如何根据参数属性在Mockito中返回不同的值?

2022-09-02 02:25:34

我测试的类接收客户端包装器:

测试的类(截图)

private ClientWrapper cw
public Tested(ClientWrapper cw) {
    this.cw = cw;
}

public String get(Request request) {
    return cw.getClient().get(request);
}

测试初始化:

ClientWrapper cw = Mockito.mock(ClientWrapper.class);
Client client = Mockito.mock(Client.class);
Mockito.when(cw.getClient()).thenReturn(client);
//Here is where I want to alternate the return value:
Mockito.when(client.get(Mockito.any(Request.class))).thenReturn("100");

在exmaple中,我总是返回“100”,但是Request有一个属性,我想根据值返回不同的值。idclient.get(Request)request.getId()

我该怎么做?


答案 1

您可以使用Mockito的答案,因此不要:

Mockito.when(client.get(Mockito.any(Request.class))).thenReturn("100");

写:

Mockito.when(client.get(Mockito.any(Request.class)))
 .thenAnswer(new Answer() {
   Object answer(InvocationOnMock invocation) {
     Object[] args = invocation.getArguments();
     Object mock = invocation.getMock();
     return "called with arguments: " + args;
   }
});

答案 2

为了正确地做到这一点,并且使用最少的代码,您必须使用,lambda表达式,并且不要忘记对lambda中的过滤器成员进行空检查(特别是如果您有多个具有相同模拟的模拟)。ArgumentMatcherArgumentMatcherArgumentMatcher

自定义参数匹配器:

private ArgumentMatcher<Request> matchRequestId(final String target) {
    return request -> request != null &&
            target.equals(request.getId());
}

用法:

 given(client.get(argThat(matchRequestId("1")))).willReturn("100");
 given(client.get(argThat(matchRequestId("2")))).willReturn("200");

推荐