我正在使用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);
我的问题是第二个匹配器会覆盖第一个匹配器,即我得到“假”&#39;在这两种情况下。
我做错了什么或如何让它成功?
这就是我最后的做法,正如@glytching
所建议的那样Mockito.when(generalUtilmock.isObjectEmpty(ArgumentMatchers。&gt; 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
}
});
答案 0 :(得分:0)
由于类型擦除,您实际上是在连续调用。见https://static.javadoc.io/org.mockito/mockito-core/2.13.0/org/mockito/Mockito.html#10
Mockito.when(generalUtilmock.isObjectEmpty(ArgumentMatchers.anyList())).thenReturn(true, false);
应该有用。
答案 1 :(得分:0)
鉴于排序(即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
}
});