【发布时间】:2022-01-22 01:59:21
【问题描述】:
我有一个对外部 API 产生影响的方法,并且我编写了异常处理程序来处理错误并在发生错误时发送对客户端友好的响应。我需要测试来自该外部 API 的非 200 OK 响应,例如错误请求、内部服务器错误,并断言应该调用异常处理程序方法以发送对客户端友好的消息。我能够成功地将外部 API 的响应模拟为错误请求,但它没有抛出 HttpStatusCodeException 理想情况下抛出 4xx 状态代码以及如何验证异常处理程序的方法调用
private final RestTemplate restTemplate = Mockito.mock(RestTemplate.class);
private final HttpHeaders httpHeaders = new HttpHeaders();
private final NotificationServiceImpl notificationService = new NotificationServiceImpl(restTemplate, httpHeaders, NOTIFICATION_API_URL, PRIMARY_NOTIFIERS, CC_NOTIFIERS, LANG, APPLICATION_NAME);
@Autowired
private ExceptionTranslator exceptionTranslator;
@Test
void testErrorOnSendNotification() {
Map<String, Instant> messages = Map.of("sample message", Instant.now());
ResponseEntity<HttpStatusCodeException> responseEntity =
new ResponseEntity<>(HttpStatus.BAD_REQUEST);
when(restTemplate.exchange(
ArgumentMatchers.anyString(),
ArgumentMatchers.any(HttpMethod.class),
ArgumentMatchers.any(),
ArgumentMatchers.<Class<HttpStatusCodeException>>any()))
.thenReturn(responseEntity);
// assertThrows(HttpStatusCodeException.class, () -> notificationService.sendNotification(messages));
verify(exceptionTranslator, times(1)).handleExceptions(any(), any());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Problem> handleExceptions(NativeWebRequest request, Exception error) {
Problem problem =
Problem.builder()
.withStatus(Status.BAD_REQUEST)
.withTitle(error.getMessage())
.withDetail(ExceptionUtils.getRootCauseMessage(error))
.build();
return create(error, problem, request);
}
【问题讨论】:
标签: java spring spring-boot mockito resttemplate