在Java中嘲笑自定义注释验证
如何正确模拟自定义验证注释?
因此,我创建了一个自定义@interface和相应的验证器类。 在验证器类中,我调用外部API检查我的DTO中注释属性的值是否有效。
我有类似的东西:
@Documented
@Constraint(validatedBy = ValueValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomValidator{
String message() default "invalid value";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
@Component
@RequiredArgsConstructor
@FieldDefaults(makeFinal=true, level=AccessLevel.PRIVATE)
public class ValueValidator implements
ConstraintValidator<MyCustomValidator, String> {
ExternalApi externalApi;
@Override
public void initialize(MyCustomValidator object) {
}
@Override
public boolean isValid(String value,
ConstraintValidatorContext cxt) {
if(!externalApi.validate(value))
return false;
else
return true;
}
}
@Data
@Valid
public class myDTORequest {
@MyCustomValidator
private String myAttribute;
}
我使用MockMVC测试控制器。现在由于外部API为无效/无法到达,因此失败了。 有什么方法可以模拟@MyCustomValidator,以免它试图调用外部API?或者更好,请模拟验证器内部的外部Appi调用?
How to properly mock custom validation annotations?
So I created a custom @interface and the corresponding validator class.
Inside the validator class, I call an external api to check if the value of the annotated attribute in my DTO is valid or not.
I have something like:
@Documented
@Constraint(validatedBy = ValueValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomValidator{
String message() default "invalid value";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
@Component
@RequiredArgsConstructor
@FieldDefaults(makeFinal=true, level=AccessLevel.PRIVATE)
public class ValueValidator implements
ConstraintValidator<MyCustomValidator, String> {
ExternalApi externalApi;
@Override
public void initialize(MyCustomValidator object) {
}
@Override
public boolean isValid(String value,
ConstraintValidatorContext cxt) {
if(!externalApi.validate(value))
return false;
else
return true;
}
}
@Data
@Valid
public class myDTORequest {
@MyCustomValidator
private String myAttribute;
}
I use mockmvc to test my controller. Now it is failing because the external api is null/unreachable.
Is there a way I could mock @MyCustomValidator so that it does not try to call an external api? Or better, mock the ExternalApi call inside the validator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论