[英]Unit testing an ExceptionHandler class
我正在尝试为 ExceptionHandler 类编写单元测试,但我不是 100% 确定如何去做。 我正在努力解决如何使用错误列表设置 MethodArgumentNotValidException 类?
@ControllerAdvice
public class InputExceptionHandler extends ResponseEntityExceptionHandler {
private static final String INVALID_CHARACTER_MESSAGE = "Fields contain invalid characters:";
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
final List<String> errorList = getErrorList(ex);
final StringBuilder errorMessage = new StringBuilder(popFirstError(errorList));
if(errorMessage.toString().contains(INVALID_CHARACTER_MESSAGE)) {
combineDuplicateErrorMessage(errorList, errorMessage);
}
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(makeBankDetailsValidationModel(errorMessage.toString()));
}
private BankDetailsValidationModel makeBankDetailsValidationModel(String validationErrorDescription){
return new BankDetailsValidationModel(false, false, validationErrorDescription, "");
}
private StringBuilder combineDuplicateErrorMessage(List<String> errorList, StringBuilder errorMessage) {
return errorList.stream()
.filter(value -> value.contains(INVALID_CHARACTER_MESSAGE))
.findFirst()
.map(value -> errorMessage.append(", ").append(value.substring(35)))
.orElse(null);
}
private String popFirstError(List<String> errorMessages) {
final String message = errorMessages.get(0);
errorMessages.remove(0);
return message;
}
private List<String> getErrorList(MethodArgumentNotValidException ex) {
return ex.getBindingResult()
.getAllErrors()
.stream()
.map(ObjectError::getDefaultMessage)
.sorted()
.collect(Collectors.toCollection(ArrayList::new));
}
}
既然您只是在测试处理程序而不是调用(这是 Sping 的工作),那么为什么不只使用模拟异常。
这样你就可以模拟你的 Exception 需要覆盖所有路径的任何属性,而不必首先想出创建 Exception 的方法......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.