简体   繁体   English

使用参数化引用类型参数模拟Spring restTemplate.exchange调用

[英]Mocking Spring restTemplate.exchange call with parameterized reference type argument

I am trying to mock a call to RestTemplate.exchange() but cant get it to work. 我试图模拟对RestTemplate.exchange()的调用,但不能让它工作。 Currently the call to exchange() hangs so I believe the actual method is being called instead of my mock. 目前对exchange()的调用挂起,所以我相信实际的方法是被调用而不是我的模拟。 The call to exchange() is as follows: 对exchange()的调用如下:

ResponseEntity<List<MyType>> response = 
    restTemplate.exchange(queryStr, 
                   HttpMethod.GET, 
                   null,
                   new ParameterizedTypeReference<List<MyType>>() {
                   });

The mocking is as follows: 嘲笑如下:

@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.

}

I have tried changing the argument matchers around so they match a broader argument types (ie. any() in place of anyString()) but I get the same behavior or an error "reference to exchange is ambiguous both method exchange(...) and method exchange(...) match". 我已经尝试更改参数匹配器,因此它们匹配更广泛的参数类型(即any()代替anyString())但我得到相同的行为或错误“对交换的引用是模糊的两种方法交换(... )和方法交换(...)匹配“。 I also get "no suitable method found for thenReturn(...) is not compatible with thenReturn(...)" along with the first error. 我也得到“找不到合适的方法,然后返回(...)与thenReturn(...)不兼容”以及第一个错误。

Thanks in advance. 提前致谢。

Found that we did not annotate the instance of the RestTemplate with @Autowired that was used in our controler. 发现我们没有使用我们的控制器中使用的@Autowired注释RestTemplate的实例。

@RestController
public class myController {

    ...

    @Autowired  // <-- Forgot this annotation.
    private RestTemplate restTemplate;

    ...

}

Now mocks work correctly. 现在模拟工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM