0
点赞
收藏
分享

微信扫一扫

如何使用PowerMockito模拟 Spring RestTemplate

忍禁 2022-02-22 阅读 80

How to Mock Spring RestTemplate using PowerMockito

  • 如何使用 PowerMockito 模拟 Spring RestTemplate
  • Spring RestTemplate 方法是使用泛型定义的。下面是用于调用Rest web 服务的方法定义。
public <T>ResponseEntity<T> exchange(
        String url,
        HttpMethod method,
        HttpEntity<?> requestEntity,
        Class<T> responseType)
    throws RestClientException
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();
}
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);
}
   PowerMockito.when(restTemplate.exchange(
         Matchers.anyString(), 
         Matchers.any(HttpMethod.class),
         Matchers.<HttpEntity<?>> any(),
         Matchers.any(Class.class)))
     .thenReturn(respEntity);

最后喜欢的小伙伴,记得关注收藏哦!😏🍭😘

举报

相关推荐

0 条评论