我试图模拟对 RestTemplate.exchange() 的调用,但无法让它工作。目前对 Exchange() 的调用挂起,因此我相信正在调用实际的方法而不是我的模拟方法。对exchange()的调用如下:
ResponseEntity<List<MyType>> response =
restTemplate.exchange(queryStr,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<MyType>>() {
});
模拟如下:
@MockBean
private RestTemplate restTemplate;
@Test
public void testMethod() throws Exception {
when(restTemplate.exchange(anyString(),
eq(HttpMethod.GET),
eq(null),
eq(new ParameterizedTypeReference<List<MyType>>(){})
)).thenReturn(new ResponseEntity<List<MyType>>(HttpStatus.OK));
// rest of test code follows.
}
我尝试更改参数匹配器,以便它们匹配更广泛的参数类型(即,any() 代替 anyString()),但我得到相同的行为或错误“对交换的引用在方法交换(...)和方法交换(...)匹配方面都不明确”。我还收到“找不到适合 thenReturn(...) 的方法与 thenReturn(...) 不兼容”以及第一个错误。
提前致谢。
最佳答案
发现我们没有使用 Controller 中使用的 @Autowired 注解 RestTemplate 实例。
@RestController
public class myController {
...
@Autowired // <-- Forgot this annotation.
private RestTemplate restTemplate;
...
}
现在模拟可以正常工作了。
关于java - 使用参数化引用类型参数模拟 Spring RestTemplate.exchange 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42428337/