首页 > 解决方案 > 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

标签: javaspring-bootjunitmockito

解决方案


有 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));

推荐阅读