[英]How can I test validation annotations?
How can I test annotation based validation? 如何测试基于注释的验证? I know that it only works with things that know how to recognize the annotations, and it seems that by default the test frameworks (JUnit, TestNG) do not recognize these.
我知道它仅适用于知道如何识别注释的事物,并且似乎默认情况下测试框架(JUnit,TestNG)无法识别这些注释。
public class Foo {
@NotNull
@Size(min = 2, max = 110)
private String description;
public method describe ( String desc ) {
this.description = desc;
}
}
update : For example how would I go about ensuring that when I attempt to set the description, that it will throw an error (if used by things that recognize the annotations) if I do Foo.new.describe( ' ' )
or Foo.new.describe( null )
. update :例如,如果我执行
Foo.new.describe( ' ' )
或Foo.new.describe( null )
如何确保在尝试设置描述时会抛出错误(如果由识别注释的事物使用Foo.new.describe( ' ' )
Foo.new.describe( null )
Your question is kinda confusing. 您的问题有点令人困惑。 I'll try to answer two different aspects of the question.
我将尝试回答该问题的两个不同方面。
How can I test validation annotations?
如何测试验证批注?
If those validation Annotations conforms to Java JSR-303 Bean Validation (which seems to be this case), you can validate those objects and make the desired assertions on Unit Tests using Hibernate Validator or another implementation. 如果这些验证注释符合Java JSR-303 Bean验证 (似乎是这种情况),则可以使用Hibernate Validator或其他实现来验证那些对象并在单元测试中进行所需的断言。
Example: 例:
public class FooTest {
private static Validator validator;
@BeforeClass
public static void setUp() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void checkIfIsNull() {
Foo foo = new Foo(); // Field is null at this point
Set<ConstraintViolation<Car>> constraintViolations = validator.validate(foo);
assertTrue(constraintViolations.size() > 0);
}
}
-- -
For example how would I go about ensuring that when I attempt to set the description, that it will throw an error (if used by things that recognize the annotations) if I do Foo.new.describe(' ') or Foo.new.describe(null)
例如,如果我执行Foo.new.describe('')或Foo.new,我将如何确保在尝试设置描述时会抛出错误(如果被识别注释的事物使用)。描述(空)
You're talking about runtime validation here, not Unit Testing. 您在这里谈论的是运行时验证,而不是单元测试。 You can check and throw the recommended exception this way:
您可以通过以下方式检查并抛出建议的异常:
public void describe(String desc) {
if (desc == null || desc.trim().isEmpty())
throw new IllegalArgumentException("[desc] parameter is null or empty");
...
}
PS: Here I'm assuming that the describe(String)
method is not actually setDescription(String)
. PS:在这里,我假设
describe(String)
方法实际上不是setDescription(String)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.