简体   繁体   中英

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. Currently the call to exchange() hangs so I believe the actual method is being called instead of my mock. The call to exchange() is as follows:

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". I also get "no suitable method found for thenReturn(...) is not compatible with thenReturn(...)" along with the first error.

Thanks in advance.

Found that we did not annotate the instance of the RestTemplate with @Autowired that was used in our controler.

@RestController
public class myController {

    ...

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

    ...

}

Now mocks work correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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