0

I just wanted to write a test for a User class to check the validation. I'm wondering that nothing is validated as annotated.

@Entity
public class User {

    @Id
    @NotBlank
    @Size(min = 2, max = 255)
    private String username;

    @NotBlank
    @Column(length = 60)
    private String password;

    public User(String username, String password) {
        this.username = username.trim();
        this.password = password;
    }
}

Now I'm trying this:

User user2 = new User("admin", "");
User user3 = new User("", "test");
User user4 = new User("", "");

And I assumed some exceptions but nothing.

  • So is there a way to test these annotations?
  • And when are those validations fired up?
Michael
  • 2,528
  • 3
  • 21
  • 54
  • Possible duplicate of [How to test validation annotations of a class using JUnit](https://stackoverflow.com/questions/29069956/how-to-test-validation-annotations-of-a-class-using-junit). – Andrew S Apr 04 '18 at 13:01

1 Answers1

3

So is there a way to test these annotations?

Yes, you need a javax.validation.Validator instance to perform a validation:

// obtain a validator
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();

// do a test
Set<ConstraintViolation<User>> constraintViolations = validator.validate(user2);
Assert.assertEquals(0, constraintViolations.size());

And when are those validations fired up?

They might be fired up at different levels.

For example, Spring can integrate validation on the controllers layer (when a request come) with @javax.validation.Valid. Or you can put a validator to fire exceptions right before sending data to the database.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142