0

I have a method in which is it using RestTemplate. I using the following code to make a call:

         final ResponseEntity<RESTResponse> responseEntity = restTemplate.exchange(uri,
                                                                               HttpMethod.POST,
                                                                               httpEntityWithHeaders,
                                                                               RESTResponse.class);

httpEntityWithHeads is of type HttpEntity<String>. I am writing a test and trying to mock RestTemplate so that when it calls the exchange method, it will throw an exception.

I am trying to mock it like this:

      when(restTemplate.exchange(
     ArgumentMatchers.contains(randomHost),
     ArgumentMatchers.eq(HttpMethod.POST),
     ArgumentMatchers.<HttpEntity<List<String>>>any(),
     ArgumentMatchers.<ParameterizedTypeReference<List<RESTResponse>>>any())

  ).thenThrow(new ResourceAccessException("Random exception message."));

But when running the test, it doesn't throw the exception, it just continues.

Any suggestions?

eghe
  • 137
  • 2
  • 14
  • Does this answer your question? [How do I mock a REST template exchange?](https://stackoverflow.com/questions/39486521/how-do-i-mock-a-rest-template-exchange) – Ryuzaki L Nov 12 '19 at 19:37

2 Answers2

0

As you said httpEntityWithHeads is of type HttpEntity<String>, so you have to stub in way that matches to HttpEntity<String>

 when(restTemplate.exchange(
 ArgumentMatchers.contains(randomHost),
 ArgumentMatchers.eq(HttpMethod.POST),
 ArgumentMatchers.<HttpEntity<String>>any(),
 ArgumentMatchers.<ParameterizedTypeReference<List<RESTResponse>>>any())

).thenThrow(new ResourceAccessException("Random exception message."));
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
0

To me seems that your last parameter is not a list it is a class, and that is why the stub is failing, I tried the following and it is working.

@Test(expected = IllegalArgumentException.class)
public void test() {
    RestTemplate restTemplate = mock(RestTemplate.class);

    when(restTemplate.exchange(anyString(), ArgumentMatchers.eq(HttpMethod.POST),
        any(HttpEntity.class), 
        any(Class.class))).thenThrow(new IllegalArgumentException("a"));

    Rest rest = new Rest(restTemplate);
    rest.call();
}


    public void call(){

       HttpEntity<Object> httpEntityWithHeaders= new HttpEntity<>(null);
       final ResponseEntity<Object> responseEntity = restTemplate.exchange("a",
        HttpMethod.POST,
        httpEntityWithHeaders,
        Object.class);
   }
Koitoer
  • 18,778
  • 7
  • 63
  • 86