Search code examples
springmockitobddresttemplate

Mockito BDD - mocking RestRemplate exchange() method


I'm trying to mock a RestTemplate exchange() call with the following code:

Test method

given(restTemplate.exchange(any(UriComponents.class), any(HttpMethod.class), any(HttpEntity.class), any(StatusResponse.class)))
            .willReturn(new ResponseEntity<>(HttpStatus.BAD_GATEWAY));

The code does not compile because:

  1. it complains that cannot resolve method willReturn(new ResponseEntity<>(HttpStatus.BAD_GATEWAY))
  2. it complains that cannot resolve method exchange(T, T, T, T)

How should I change the signature to make it work? Thanks.


Solution

  • The 1st argument of exchange (url) should be eq("url") or anyString() (assumning that "url" is the value you're using in your test).

    The 4th argument (response class) should be eq(StatusResponse.class) or any(Class.class).