How to test ConstraintViolationException with assertJ?

275 views Asked by At

If I have a bean like

@Data
@Validated
@EqualsAndHashCode(callSuper = true)
@Document(collection = "Xxx")
public class XxxDocument extends Zzz {
    @Min(0)
    @Max(255)
    private Integer aProperty;
}

How can I write a test using assertJ that checks whether the setting of aProperty raised a ConstraintViolationException? I would like to use Lombok's @Data annotation to avoid writing the getters and setters where I could declare that the setter throws this exception.

2

There are 2 answers

0
Stefano Cordio On

You could achieve that with AssertJ and some manual work, but assertj-bean-validation might be a better candidate for it.

0
Jin Kwon On

As @StefanoCordio mentioned, with assertj-bean-validation, you can do this.

XxxDocument document = new XxxDocument(-1);

assertThatBean(document).isValid();                     // should fail
assertThatBean(document).hasValidProperty("aProperty"); // should fail

assertThatProperty(0).isValidFor(XxxDocument.class, "aProperty");