使用Mockito 2.7.5对同一模拟进行多次调用的ArgumentMatchers

用户1792899

我正在使用Mockito 2.7.5。我需要模拟对方法的调用,并根据list参数包含的对象的类型确定返回值。我正在这样做:

Mockito.when(generalUtilmock.isObjectEmpty(
    ArgumentMatchers.<List<AccountValidationResponseDTO>>any())
).thenReturn(true);

Mockito.when(generalUtilmock.isObjectEmpty(
    ArgumentMatchers.<List<License>>any())
).thenReturn(false);

我的问题是第二个匹配器会覆盖第一个匹配器,即在两种情况下我都得到“假”。

我做错了什么或如何使它起作用?


正如@glytching所建议的,这就是我最后做的方法

Mockito.when(generalUtilmock.isObjectEmpty(ArgumentMatchers。> any()))。thenAnswer(new Answer(){

public Object answer(InvocationOnMock invocation) {
  Object[] args = invocation.getArguments();
  // if args contains a List<License> then return false
  if(args[0] instanceof List){
    ArrayList o = (ArrayList)args[0];
    if(o!=null && !o.isEmpty()) {
      if (o.get(0) instanceof AccountValidationResponseDTO)
        return true;
      else if (o.get(0) instanceof License)
        return false;
    }
  }
  return false;
  // if args contains a List<AccountValidationResponseDTO> then return true
}

});

涂鸦

鉴于排序(即when(...).thenReturn(true, false))不足以满足您的需要,您将不得不使用它thenAnswer来测试给定的参数并相应地返回一个值。

例如:

when(generalUtilmock.isObjectEmpty(ArgumentMatchers.<List<License>>any()))).thenAnswer(new Answer() {

    public Object answer(InvocationOnMock invocation) {
        Object[] args = invocation.getArguments();

        // if args contains a List<License> then return false
        // if args contains a List<AccountValidationResponseDTO> then return true
    }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章