如何使用PowerMockito模拟 Spring RestTemplate

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

调用 Rest web 服务的示例代码

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();
}

模拟 RestTemplate 的 Junit 测试方法

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);
}

您可以在不指定 HttpEntity 的请求类的情况下设置期望值。

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

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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值