java Mockito不适用于RestTemplate
我正在使用mockito模拟RestTemplate交换调用。下面是我所使用的,但它没有使用模拟的RestTemplate
模拟呼叫
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, userId);
嘲弄的复述如下
Mockito.when(restTemplate.exchange(
Matchers.anyString(),
Matchers.any(HttpMethod.class),
Matchers.<HttpEntity<?>> any(),
Matchers.<Class<String>> any(),
Matchers.anyString())).
thenReturn(responseEntity);
知道这里出了什么问题吗?由于我模拟的是静态内容,因此它使用@RunWith(PowerMockRunner.class)运行
# 1 楼答案
signature将
Object...
作为最后一个参数,因此必须使用anyVarArg()
。这在这里工作得很好:注意:使用
anyVarArg
和强制转换(Object) Matches.anyVarArgs()
也可以避免不明确的方法错误# 2 楼答案
因为我正在用我的方法做以下事情。模拟的交换方法没有绑定
因此,我将源代码更改为以下内容,并创建一个方法来创建RestTempate实例
并在测试源中执行以下操作
# 3 楼答案
我也在为同样的问题挣扎。这是一个对我有用的笑话
注意,我使用varargs作为anyString()