java - 在运行时使 @Valid 注释方法失败
问题描述
我有一个像这样的抽象类:
public abstract class Request implements RequestDto {
private final req ipwRequest = new IpwRequestMetadataDto();
@Valid
@Override
public String getRequestId() {
if (isRequestIdNull() && req.getRequestId() == null) {
return null;
}
if (!isRequestIdNull() && req.getRequestId() != null && req.getRequestId().length() > 0) {
return req.getRequestId();
}
String errorMessage = "Request id should " +
(isRequestIdNull() ? "" : "not ") +
"be null";
throw new ConstraintViolationException(errorMessage, Collections.emptySet());
}
protected abstract boolean isRequestIdNull();
}
这个类可以被其他两个类覆盖,每个类都覆盖isRequestIdNull
。
我尝试通过使用这样的验证器来测试它是否正常工作:
@Test
public void testCreateRequest() {
var dto = new CreateRequest();
dto.setRequestId("11111");
Set<ConstraintViolation<CreateRequest>> constraintViolations = validator.validate(dto);
// Assert
assertNotEquals(1, constraintViolations.size());
}
getRequestId 在调用验证器时被调用,但不是添加到constraintViolations
,它只是抛出异常并崩溃。
如何添加到 constraintViolations 而不是抛出异常。
解决方案
将 constraintViolations 作为参数传递给 getRequestId,并在函数 getRequestId 内有一个标志是抛出异常还是添加到 constraintViolations 列表中
推荐阅读
- python - Android 客户端,Python 服务器 - AES + RSA 加密 - 结果:垫块损坏
- html - 如何取同一个选择器的一个元素?
- ruby - 如何在没有 Raspberry Pi 的情况下为 Raspberry Pi(主要是 GPIO)开发和测试应用程序?
- django - 如何云托管一个只有 3 人左右的人会使用的网站,或者如何保护它免受 DDoS 攻击?
- java - 使用 Spring JPA 通过会话登录后获取数据
- css - 从公共文件夹 reactjs 访问图像
- html - 如何使用 CSS 调整卡片大小
- python - 为什么我的文件读取功能只读取奇数行?
- python - 在 Visual Studio 2017 中使用 NetworkX 读取 GraphML 文件时出现 KeyError 异常,但在 Spyder 中没有
- google-sheets - 特定日期的 GoogleFinance Beta 版?