Tarun Maganti
Tarun Maganti

Reputation: 3076

How to check if a constraint exists in a Java class?

I have written a test class for an another class which used Hibernate Constraints. In the test class, I verify if the constraint is violated or not.

But what if while refactoring the original class the programmer forgot to annotate the class with constraints. How to test if a constraint exists or not.


To clarify, I have a class defined as such -

Class User {
    @Email
    String email;

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

    /*Getters and Setters Omitted*/
}

Checking for property String email; to have the constraint @Email

Upvotes: 2

Views: 928

Answers (2)

davidxxx
davidxxx

Reputation: 131376

What you try to do is rather cumbersome and it is not really a unit test as a unit test should valid a specific behavior of a component.
Here, you want to validate the structure of the class.

If you are afraid that someone removes the validator annotation, I think that you should modify your unit test to check that if the email is not provided as expected for an entity user you are validating, the validation provides a ConstraintViolation instance with the good message/path.

Upvotes: 3

Matt
Matt

Reputation: 3760

You could do this using reflection. There's a nice tutorial here:

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

Basically it would work something like this:

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());
    }
}

I haven't tested this code, but it should give you enough to go on.

Upvotes: 3

Related Questions