I have been looking at using jsr303 annotations to mark up some of my beans. The good news is that both Hibernate and Springplaynicely with these annotations, and will validate them at appropriate times. The bad news is that the examplesoftesting these annotations that I have found online so far look cumbersome and awkward.
Let’s take a simple example:
simple java bean with a single jsr303 annotation
12345678910
publicclassSimpleBean{@NotNullprivateLongid;privateStringname;publicSimpleBean(Longid,Stringname){this.id=id;this.name=name;}// getters and setters...}
This is fine so far and we have the possibility that the constructor could be passed a null id. So, let’s write a unit test that ensures our validation will barf.
And our new-look test spits out the following upon failure:
123
java.lang.AssertionError:
Expected: no jsr303 validation violations
but: was <[ConstraintViolationImpl{interpolatedMessage='may not be null', propertyPath=id, rootBeanClass=class com.example.SimpleBean, messageTemplate='{javax.validation.constraints.NotNull.message}'}]>
There. Much nicer. Not only do we know that the test failed, but we are immediately told how it failed.