Juan
Juan

Reputation: 31

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.

Upvotes: 1

Views: 3738

Answers (1)

Juan
Juan

Reputation: 31

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.

Upvotes: 2

Related Questions