Mockito mocking restTemplate.postForEntity

22,607

Solution 1

The following code works for me - when(mockRestTemplate.postForEntity(anyString(), any(), eq(String.class))).thenReturn(response);

Solution 2

This is what worked for me Firstly a resttemplate needs to be mocked in the test class

@Mock 
private RestTemplate mockRestTemplate;

Since ResponseEntity returns an Object create another method that returns the expected response wrapped in ResponseEntity

private ResponseEntity<Object> generateResponseEntityObject(String response, HttpStatus httpStatus){
    return new ResponseEntity<>(response, httpStatus);
}

In your test case, you can now mock the expected response as follows

String string = "result";
when(mockRestTemplate.postForEntity(anyString(), any(), any()))
        .thenReturn(generateResponseEntityObject(string, HttpStatus.OK));
Share:
22,607
Dax Durax
Author by

Dax Durax

Updated on October 08, 2020

Comments

  • Dax Durax
    Dax Durax over 3 years

    I am trying to mock restTemplate.postForEntity method,

    The actual method call is:

    URI myUri = new URI(myString);
    HttpEntity<String> myEntity ...
    
    
    String myResponse = restTemplate.postForEntity(myUri, myEntity, String.class);
    

    What I have in my test class is:

    Mockito.when(restTemplate.postForEntity(any(URI.class), any(HttpEntity.class), eq(String.class))).thenReturn(response);
    

    This does not work; I have tried several other permutations with no success either. Any suggestions appreciated, thanks.

    By this does not work I mean that the actual method is called and not the mocked method (so the desired result is not returned etc.)

  • user09
    user09 about 7 years
    What if you autowire TestTemplate in your service class?
  • parthivrshah
    parthivrshah about 6 years
    How are you creating the response object? Can you provide the example?
  • Parthasarathy B
    Parthasarathy B almost 5 years
    private ResponseEntity<String> createPaymentConfirmationResponse(){ return ResponseEntity.ok("something"); }
  • pixel
    pixel over 2 years
    this is not working at all, not even compiling. Cannot resolve method any()
  • pixel
    pixel over 2 years
    this is not working at all, not even compiling. Cannot resolve method any()