I have a Spring project, I use hibernate validator and have a Junit test class which uses the following code:

Set<ConstraintViolation<Rule>> constraintViolations =  validator.validateProperty(myObject, "query");

assertEquals(1, constraintViolations.size());

However, I see that this is not a good way of testing. I have a NotBlank annotation and that test class checks whether it works or not. However if I put any other constraint that is violated than constraintViolations.size() will be 2.

My question is that: How can I check whether NotBlank is violated or not?

有帮助吗?

解决方案

You could use:

constraintViolation.getConstraintDescriptor().getAnnotation()

to get type of the annotation used to produce this violatation and then compare it with what you expect.

In case of multiple violatation you might need to iterate over the collection.

So, in the end

assertTrue(isExpectedConstraintViolated(NotBlank.class, constraintViolations))



public boolean isExpectedConstraintViolated(Class<?> clazz, Set<ConstraintViolation<Rule>> constraintViolations){
    for(ConstraintViolation<Rule> violaton: constraintViolations){
        if(clazz.equals(violaton.getConstraintDescriptor().getAnnotation().annotationType())){
            return true;
        }
    }
    return false;
}

should do the job.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top