提问者:小点点

try和catch块的JUnit代码覆盖率


我正在尝试为下面的代码编写一个 JUnit,但我无法在 Junit 代码覆盖率中涵盖 catch 块,并且自一周以来我就面临此问题,任何关于涵盖此块的建议。

@Autowired
ErrorHandler error;
try {

        } catch (HttpClientErrorException e) {
            errorHandler.error(ErrorMessages.EPO_VALIDATEQ_ERROR_08, e.getResponseBodyAsString());
        } catch (HttpServerErrorException e) {
            throw new ServiceException(ErrorMessages.EPO_SYSTEM_ERROR, e.getMessage(), url);
        }
public void error(ResolvableErrorEnum error, String responseBody) {
        throw new ServiceException(error);
    }
@Test(expected = ServiceException.class)
    public void test_callUpdateCart_Exception() {
        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);
    }


共1个答案

匿名用户

尝试模拟HttpClientErrorException并使用doThrow()

HttpClientErrorException exception = mock(HttpClientErrorException.class);
when(exception.getResponseBodyAsString()).thenReturn("BAD REQUEST");
doThrow(exception).when(restTemplate).postForObject(anyString(), any(), eq(JsonNode.class));