【问题标题】:Throwing a exception with custom message from Mockito Junit testing使用来自 Mockito Junit 测试的自定义消息引发异常
【发布时间】:2021-06-05 03:04:59
【问题描述】:
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);
}

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

org.mockito.exceptions.base.MockitoException:
已检查的异常对此方法无效!
无效:java.lang.Exception:未授权

【问题讨论】:

    标签: java spring-boot junit mockito


    【解决方案1】:

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

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

    如果你想存根方法以输入通用情况的 catch 块,你需要抛出一个RuntimeException,它是unchecked,因此不受“抛出”限制。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      相关资源
      最近更新 更多