【发布时间】: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