java - HttpsStatusCodeException 返回 null:Spring Boot
问题描述
在这里,我使用的是 Junit5,并且我正在模拟其余模板调用以返回 HttpClientErrorException,但是会引发空指针异常。我无法弄清楚为什么在指定的行返回 Null。
休息电话
ResponseEntity<Object> obj;
try{
obj=restTemplate.postForEntity(url, requestObj, Object.class);
}catch(HttpStatusCodeException ex){
ex.getMessage();
throw new CustomError(ex.getStatusCode()); //ex.getStatusCode is Null and throws Null Pointer Exception
}catch(Exception ex){
throw....
}
测试
@Mock
RestTemplate restTemplate;
when(restTemplate.postForEntity(anyString(),any(),eq(Object.class)))
.thenThrow(HttpClientErrorException.class);
HttpStatus status= Assertions.assertThrows(CustomError.class,()->obj.methodName()).getHttpStatus();
Assertions.assertTrue(status.is4xxClientError()); //500 is thrown Null pointer exception
解决方案
有 2 个选项可以解决此问题,您需要提供一个 mockHttpClientErrorException
及其正在使用的方法,或者您需要将异常对象的实例传递给 throw 语句。
HttpClientErrorException mockedException = mock(HttpClientErrorException.class);
when(mockedException.getStatusCode()).thenReturn(HttpStatus.NOT_FOUND);
...
when(restTemplate.postForEntity(anyString(),any(),eq(Object.class)))
.thenThrow(mockedException);
或者
when(restTemplate.postForEntity(anyString(),any(),eq(Object.class)))
.thenThrow( new HttpClientErrorException(HttpStatus.NOT_FOUND));
推荐阅读
- jsf - 部署期间的 Java EE 严重错误:java.lang.NullPointerException
- mysql - 如何将计算值与选择查询中的值一起插入?
- xbox-one - Xbox Live 聊天机器人示例
- java - 云环境中的异步任务
- firebase - 禁用动态链接的手动构建 url
- .htaccess - htaccess,如果子域不是“dev”,请按照以下说明操作
- javascript - 像在 vscode 文件中一样搜索的 javascript 函数
- electron - 电子根本不会启动
- json - Flutter:如何根据声明为 JSON 显示的数据着色
- vba - SAP 进程会话 txt 不接受输入列