By kswaughs | Tuesday, September 15, 2015

How to Mock Spring RestTemplate using PowerMockito

Spring RestTemplate methods are defined using generics. Below is the method definition which is used to call rest service.

public <T>ResponseEntity<T> exchange(
        String url,
        HttpMethod method,
        HttpEntity<?> requestEntity,
        Class<T> responseType)
    throws RestClientException

Sample code to call Rest web service
public RestResponse callRestService(RestRequest request) {
   
     HttpHeaders headers = new HttpHeaders();
     headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
     headers.setContentType(MediaType.APPLICATION_JSON);
 
     HttpEntity<RestRequest> entityReq = new HttpEntity<RestRequest>(
          request, headers);

     RestTemplate template = new RestTemplate();

     ResponseEntity<RestResponse> respEntity = template.
          exchange("RestSvcUrl", HttpMethod.POST, entityReq, RestResponse.class);
 
     return respEntity.getBody();
}

Junit Test method to mock RestTemplate
public void mockRestTemplate() throws Exception {
 
    // Mock RestTemplate 
    RestTemplate restTemplate = PowerMockito.mock(RestTemplate.class);
    PowerMockito.whenNew(RestTemplate.class).withNoArguments().
          thenReturn(restTemplate);
 
    // Create sample test response  
    RestResponse testResponse = new  RestResponse();
    // Build the response with required values
    /**  Call setters of testResponse   **/ 
    ResponseEntity<RestResponse> respEntity = new ResponseEntity<RestResponse>(
          testResponse, HttpStatus.ACCEPTED);
 
    // Set expectation on mock RestTemplate
    PowerMockito.when(restTemplate.exchange(
          Matchers.anyString(), 
          Matchers.any(HttpMethod.class),
          Matchers.<HttpEntity<RestRequest>> any(),
          Matchers.any(Class.class)))
      .thenReturn(respEntity);
}

You can set expectation without specifying the request class of the HttpEntity.

   PowerMockito.when(restTemplate.exchange(
         Matchers.anyString(), 
         Matchers.any(HttpMethod.class),
         Matchers.<HttpEntity<?>> any(),
         Matchers.any(Class.class)))
     .thenReturn(respEntity);

Recommend this on


4 comments:

  1. What is pom dependency?

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Can you please explain how to use powermock with WebApplicationContext setup?

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete