如何检查Java类中是否存在约束?

时间:2017-03-14 05:11:30

标签: java hibernate unit-testing

我为另一个使用Hibernate Constraints的类编写了一个测试类。在测试类中,我验证是否违反了约束。

但是,如果在重构原始类时,程序员忘记使用约束来注​​释该类。如何测试约束是否存在。

为了澄清,我有一个如此定义的类 -

Class User {
    @Email
    String email;

    @NumberFormat
    @Length(min = 8, max = 16)
    String phoneNumber;

    /*Getters and Setters Omitted*/
}

检查属性String email;是否具有约束@Email

2 个答案:

答案 0 :(得分:3)

你可以用反射做到这一点。这里有一个很好的教程:

http://tutorials.jenkov.com/java-reflection/annotations.html

基本上它可以这样工作:

Class myEntity = MyEntity.class;
Field someField = myEntity.getField("someField");
Annotation[] annotations = someField.getAnnotations();

for(Annotation annotation : annotations){
    if(annotation instanceof Length){
        Length length = (Length) annotation;
        System.out.println("value: " + length.value());
    }
}

我还没有测试过这段代码,但它应该足以让你继续下去。

答案 1 :(得分:3)

你尝试做的事情相当繁琐,并不是真正的单元测试 单元测试应该对组件的特定行为有效。
在这里,您要验证类的结构。

如果您害怕有人删除验证器注释,我认为您应该修改单元测试以检查如果没有按照您要验证的实体用户的预期提供电子邮件,则验证提供 具有良好消息/路径的ConstraintViolation实例。