我试图遵循下面文章中的说明,尝试实现一个简单的注释,只是为了测试字符串是否具有一定的长度作为测试。我的目标是让这个注释在运行时抛出一个异常,如果字符串不满足某些条件。
https://dzone.com/articles/create-your-own-constraint-with-bean-validation-20
我可以将注释添加到代码中,一切都可以正常编译和构建。但是,当我尝试从单元测试中调用它时,无论我做什么,我都无法运行验证。我觉得我错过了一些明显的东西,但我不知道它是什么。请注意,这是一个Java SE后端服务,因此没有UI组件。让我们举一个例子(我知道这个例子已经存在,用来检查一个字符串是null还是空的)
下面是界面:
@Documented
@Constraint(validatedBy = {NotEmptyValidator.class})
@Target({METHOD, FIELD, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
public @interface NotEmpty {
Class<?>[] groups() default {};
String message() default "test message";
Class<? extends Payload>[] payload() default {};
}下面是验证器:
public class NotEmptyValidator implements ConstraintValidator<NotEmpty, String> {
@Override
public void initialize(final NotEmpty notEmpty) {
}
@Override
public boolean isValid(String notEmptyField, ConstraintValidatorContext constraintValidatorContext) {
return !Strings.isNullOrEmpty(notEmptyField);
}}
请注意,保留设置为运行时,但当我在为空字符串的字符串参数上运行单元测试时,它实际上并不验证。我如何真正打开这个验证并让它运行呢?
例如,如果我有一个随机的实用程序方法
public static String testAnnotation(@NotEmpty final String foo) {
return foo + "bar"
}如果我从单元测试中调用它,即使字符串为null或空,验证也不会运行。任何帮助都将不胜感激!
发布于 2018-08-31 04:05:40
如果我理解正确的话,您希望在以类似于以下示例的方式调用testAnnotation()方法时收到验证异常:
public void doThings(){
// some code
testAnnotation("");
//no exception is thrown and code proceed to next statements...
// more code
}如果是这样,那么问题是验证将不会发生,而是它本身。您需要显式地对某些bean执行验证:
public void doValidationManually() {
Validator validator = Validation.byDefaultProvider()
.configure()
.buildValidatorFactory()
.getValidator();
MyObj obj = new MyObj();
// some more initialization...
Set<ConstraintViolation<MyObj>> violations = validator.validate( obj );
// make any decisions based on the set of violations.
}验证器可以在方法外部初始化,而不是每次需要验证时都创建。
在方法参数验证的情况下,Bean验证不支持静态方法,但在非静态方法的情况下,您需要再次手动运行验证:
public void doMethodValidationManually() throws NoSuchMethodException {
ExecutableValidator validator = Validation.byDefaultProvider()
.configure()
.buildValidatorFactory()
.getValidator().forExecutables();
Method testAnnotationMethod = MyObj.class.getDeclaredMethod( "testAnnotation", String.class );
MyObj obj = new MyObj();
Set<ConstraintViolation<MyObj>> violations = validator.validateParameters(
obj, // an object on which a method is expected to be called
testAnnotationMethod, // the method which parameters we want to validate
new Object[] { "" } // an array of parameters that we expect to pass to the method
);
// make any decisions based on the set of violations.
}或者您应该在容器中运行您的代码,在这种情况下,对您的方法的验证将由容器自动委托和执行。有关这方面的更多信息,请参阅Bean Validation with CDI或使用Spring。
https://stackoverflow.com/questions/52087687
复制相似问题