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

时间:2016-05-08 07:20:04

标签: java mockito

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

测试类(snippest)

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",但请求有一个属性id,我想基于{{1}向client.get(Request)返回不同的值}值。

我该怎么做?

3 个答案:

答案 0 :(得分:20)

您可以使用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;
   }
});

答案 1 :(得分:5)

您可以创建class base(object): def __init__(self, base_param): self.base_param = base_param class child1(base): # inherited from base class def __init__(self, child_param, *args) # *args for non-keyword args self.child_param = child_param super(child1, self).__init__(*args) # call __init__ of the base class and initialize it with a NON-KEYWORD arg class child2(base): def __init__(self, child_param, **kwargs): self.child_param = child_param super(child2, self).__init__(**kwargs) # call __init__ of the base class and initialize it with a KEYWORD arg c1 = child1(1,0) c2 = child2(1,base_param=0) print c1.base_param # 0 print c1.child_param # 1 print c2.base_param # 0 print c2.child_param # 1 ,以便通过ID匹配ArgumentMatcher

所以参数匹配器就是这样的:

import org.mockito.ArgumentMatcher;

Request

然后你就可以使用它:

public class IsRequestWithId extends ArgumentMatcher<Request> {
    private final int id;

    public IsRequestWithId(int id) {
        this.id = id;
    }

    @Override
    public boolean matches(Object arg) {
        Request request = (Request)arg;
        return id == request.getId();
    }
}

否则使用Mockito.when(client.get(Mockito.argThat(new IsRequestWithId(1)))).thenReturn("100"); Mockito.when(client.get(Mockito.argThat(new IsRequestWithId(2)))).thenReturn("200"); 也可以,但使用Answer可以让代码更具“声明性”。

答案 2 :(得分:4)

为了做到正确并且使用最少的代码,您必须使用ArgumentMatcher,lambda表达式&amp; 不要忘记ArgumentMatcher lambda中的过滤器成员进行空检查(特别是如果您有多个具有相同ArgumentMatcher的模拟器)。< / p>

自定义参数匹配器:

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");