使用来自 Mockito Junit 测试的自定义消息抛出异常

Throwing a exception with custom message from Mockito Junit testing

try {
        response = restTemplate.postForEntity(endPoint, request, Object.class);
        lOGGER.info("response is " + response);
        
    } catch (Exception e) {
        lOGGER.error("Exception :" + e.getMessage());
        if ((e.getMessage().contains("401") || e.getMessage().contains("Unauthorized")) ) {
            ServiceImpl.evictTokenCache("authToken");
            getData(requestDto);
        } else {
            throw new CustomException(e.getMessage());
        }

以上是我的服务和尝试为catch子句编写测试用例,我的测试用例是

@Test()
public void getExceptionTest() throws Exception {
    RequestDto requestDto = new RequestDto();
    requestDto.setPage("1");
    AuthConfig authDTO = new AuthConfig();
    authDTO.setUrl("Url");
    Mockito.when(restTemplate.postForEntity(Mockito.anyString(), Mockito.any(), Mockito.any())).thenThrow((new Exception("Unauthorized")));
    ResponseDTO response = restCallUtil.getData(requestDto);
    assertNull(response);
}

我在 catch 块中尝试做的是,每当我收到未经授权的异常时,我都会清除缓存并再次调用相同的方法。因此,为了从我的测试 class 中测试 catch 块,我试图抛出消息为“未经授权”的异常,但是当我 运行 测试用例时,我得到

org.mockito.exceptions.base.MockitoException:
Checked exception is invalid for this method!
Invalid: java.lang.Exception: Unauthorized

首先要注意的是 Exception 的实例不是 RuntimeException 的实例是 checked 异常。因此,方法抛出泛型 Exception 的唯一方法是方法签名包含“throws Exception”或“throws Throwable”。

那么..为什么会出现此错误?您正在对抛出 RestClientExceptionpostForEntity 方法进行存根,并且 Exception 不是 RestClientException 的实例。因此,您的存根无效。

如果您想存根方法以便输入通用案例​​的 catch 块,您将需要抛出一个 RuntimeException,即 未检查,因此不受“抛出”限制。

也就是说,在原始方法中仅捕获 RestClientException 可能更明智。如果您想捕获一些 RuntimeException,那么您可能已经知道那是什么并具体捕获它。