How to test validation annotations of a class using JUnit?

后端 未结 9 1165
盖世英雄少女心
盖世英雄少女心 2020-12-07 17:29

I need to test the validation annotations but it looks like they do not work. I am not sure if the JUnit is also correct. Currently, the test will be passed but as you can s

9条回答
  •  余生分开走
    2020-12-07 18:09

    I found a simple way to test validation annotations using javax:

    Declare the Validator at Class level:

    private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    

    Then in your test simply call it on the object you require validation on, with what exception you are validating:

    Set violations = validator.validate(theInstanceOfTheClassYouAreValidating);
    

    Then simply assert the number of expected violations:

    assertThat(violations.size()).isEqualTo(1);
    

    You will need to add this to your dependencies (gradle):

    compile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'

提交回复
热议问题