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);
最后喜欢的小伙伴,记得关注收藏哦!😏🍭😘