我有两个方法,我想调用第一个public方法,它反过来会调用一个private方法,在private方法中我想调用一个外部服务,并模拟其中get请求的500个内部服务错误。我知道如何模仿整个私有方法,但这行不通,我想看看在那里发生了什么,特别是当我从外部服务得到一个500回来。
下面是我正在测试的两种方法。。
@Resource(name = "serviceRestTemplate")
private OAuth2RestTemplate serviceRestTemplate;
public ResponseEntity<Cargo> getById(String id) throws MyException {
UriComponentsBuilder newUri = UriComponentsBuilder
.fromHttpUrl(url + id + HEADER_URI);
ResponseEntity<String> responseEntity = this.callNewService(newUri, HttpMethod.GET);
// more irrelivent code...
}
private ResponseEntity<String> callNewService(UriComponentsBuilder uriBuilder, HttpMethod method) throws MyException {
ResponseEntity<String> responseEntity = null;
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<>(headers);
responseEntity = serviceRestTemplate.exchange(uriBuilder.toUriString(),
method, requestEntity, String.class);
}catch(HttpClientErrorException httpClientErrorException) {
LOGGER.error("Error when calling Service. {} ", uriBuilder.toUriString());
LOGGER.error("Error message from HttpClientErrorException . {} ", httpClientErrorException.getMessage());
throw buildException(httpClientErrorException.getMessage(), httpClientErrorException.getRawStatusCode());
}
if(null != responseEntity
&& responseEntity.getStatusCode().is2xxSuccessful()
&& EDMRESTServiceUtilities.isJsonValid(responseEntity.getBody())) {
LOGGER.info("Service response: {}", responseEntity.getBody());
return responseEntity;
}else {
LOGGER.error("Error response from Service. {} ", uriBuilder.toUriString());
throw buildException(SERVICE_ERROR_MESSAGE, HttpStatus.INTERNAL_SERVER_ERROR.value());
}
}
1条答案
按热度按时间uqzxnwby1#
你可以嘲笑你的朋友
serviceRestTemplate
还有打电话给exchange
在测试中,将注入方法更改为构造函数注入,这样可以更容易地在类中使用mock。