How to test validation annotations of a class using JUnit?

后端 未结 9 1137
盖世英雄少女心
盖世英雄少女心 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:03

    First thanks @Eis for the answer, it helped me. It's a good way to fail the test, but I wanted a bit more "life-like" behaviour. At runtime an exception would be thrown so I came up with this:

    /**
     * Simulates the behaviour of bean-validation e.g. @NotNull
     */
    private void validateBean(Object bean) throws AssertionError {
        Optional> violation = validator.validate(bean).stream().findFirst();
        if (violation.isPresent()) {
            throw new ValidationException(violation.get().getMessage());
        }
    }
    

    Have an entity with validation:

    @Data
    public class MyEntity {
    
    @NotBlank(message = "Name cannot be empty!")
    private String name;
    
    }
    

    In a test you can pass an instance with invalid attributes and expect an exception:

    private Validator validator;
    
    @Before
    public void setUp() {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }
    
    @Test(expected = ValidationException.class)
    public void testValidationWhenNoNameThenThrowException() {
        validateBean(new Entity.setName(""));
    }
    

提交回复
热议问题