Java 如何解决使用Mockito.any()时的混淆?
我想模拟使用不同参数调用两次的方法的结果 我用了这个密码Java 如何解决使用Mockito.any()时的混淆?,java,unit-testing,junit,mockito,Java,Unit Testing,Junit,Mockito,我想模拟使用不同参数调用两次的方法的结果 我用了这个密码 Mockito.when(rt.exchange(Mockito.anyString(), Mockito.any(HttpMethod.class), Mockito.<HttpEntity<?>> any(), Mockito.<Class<String>> any())).thenReturn(response); Mockito.when(rt.exchange(Mockito.a
Mockito.when(rt.exchange(Mockito.anyString(), Mockito.any(HttpMethod.class), Mockito.<HttpEntity<?>> any(), Mockito.<Class<String>> any())).thenReturn(response);
Mockito.when(rt.exchange(Mockito.anyString(), Mockito.any(HttpMethod.class), Mockito.<HttpEntity<?>>any(), Matchers.<Class<InfsEspecificasDTO>> any())).thenReturn(responseInfoEsp);
然而,当我启动测试时,第一个模拟总是被执行的。
如何解决这一困惑。我尝试将第二个模拟中的第四个参数指定为infsSpecificAsdTo.class,但我得到了
无效使用MatcherException
我怎样才能解决困惑?试试doAnswer解决方案。前三个参数无关紧要,您只需检查最后一个参数的实例:
when(rt.exchange(anyString(), any(HttpMethod.class), any(), any()))
.thenAnswer((invocation) -> {
Object paramToCheck = invocation.getArguments()[3];
if(paramToCheck instanceof String){
return response;
}else if (paramToCheck instanceof InfsEspecificasDTO){
return responseInfoEsp;
}
return null;
});