gpt4 book ai didi

java - 无法覆盖catch block 代码覆盖率

转载 作者:行者123 更新时间:2023-12-01 16:13:24 25 4
gpt4 key购买 nike

我无法在 Junit 代码覆盖率中覆盖以下 HttpClientErrorException catch block 。我怎样才能做到这一点?

代码

@Autowired
private ExceptionHandlerService errorHandler;
public CartResponse callUpdateCart(AddToCartRequest request) {
String url = Utils.formatHttpUrl(cartbaseUrl, CART_UPDATE_CART);
try {

HttpEntity<?> entity = new HttpEntity<>(request);
JsonNode jsonNode = restTemplate.postForObject(url, entity, JsonNode.class);
if (jsonNode.has(Constants.CONTENT) && !jsonNode.path(Constants.CONTENT).path(Constants.PAYLOAD).isMissingNode()) {
jsonNode = jsonNode.path(Constants.PAYLOAD).get(Constants.PAYLOAD);
} else {
errorHandler.error(ErrorMessages.EPO_VALIDATEQ_ERROR_08, jsonNode);
}

return JsonService.getObjectFromJson(jsonNode, CartResponse.class);
} catch (HttpClientErrorException e) {
errorHandler.error(ErrorMessages.EPO_VALIDATEQ_ERROR_08, e.getResponseBodyAsString());
return null;
} catch (HttpServerErrorException e) {
throw new ServiceException(ErrorMessages.EPO_SYSTEM_ERROR, e.getMessage(), url);
}
}

异常处理服务

@Override
public void error(ResolvableErrorEnum error, String responseBody) {
JsonNode response = JsonService.getObjectFromJson(responseBody, JsonNode.class);
if (null != response && null != response.get(Constants.ERROR)) {
ServiceError serviceError = JsonService.getObjectFromJsonNode(response.get(Constants.ERROR), ServiceError.class);
error(error, serviceError.getErrorId(), serviceError.getMessage());
}

throw new ServiceException(error);
}

junit

@Test(expected = ServiceException.class)
public void test_callUpdateCart_Exception() throws IOException {
AddToCartRequest req = createAddToCartRequest();

String responseBodyStr = "{\"error\":{\"errorId\":\"Service-I-1003\",\"message\":\"Error returned from downstream system.\",\"traceCode\":\"CART;400\",\"details\":[{\"code\":\"400\",\"message\":\"400 Bad Request\"},{\"code\":\"DTV_CAT_ERR_002\",\"message\":\"Error in getting response from catalog.\",\"traceCode\":\"CART;400\"}]}}\r\n";
byte[] body = responseBodyStr.getBytes(StandardCharsets.UTF_8);
HttpClientErrorException e = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "BAD REQUEST", body,
StandardCharsets.UTF_8);

when(restTemplate.postForObject(Mockito.anyString(), Mockito.<HttpEntity<?>>any(), Mockito.eq(JsonNode.class)))
.thenThrow(e);
client.callUpdateCart(req);
}

错误

enter image description here

最佳答案

似乎 mockito.when() 无法正常工作,因为它看起来没有抛出您要求它抛出的异常。我也遇到过类似的问题,用mockito匹配器修补通常可以解决这些问题。

您可以查看this page有关“扩展”或限制参数匹配器的更多信息。

我认为以下解决方案可行:

when(restTemplate.postForObject(Mockito.anyString(), Mockito.any(HttpEntity.class), Mockito.any(JsonNode.class)))
.thenThrow(e);

关于java - 无法覆盖catch block 代码覆盖率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62471430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com