java - Testing validation constraints -


the hibernate validator documentation has simple getting started guide outlines testing validation rules.

the relevant chunk is

@test public void manufacturerisnull() {     car car = new car(null, "dd-ab-123", 4);      set<constraintviolation<car>> constraintviolations =         validator.validate(car);      assertequals(1, constraintviolations.size());     assertequals("may not null", constraintviolations.iterator().next().getmessage()); } 

it seems me vague route test if notnull constraint has been violated.

my simple solution like

public static <t> boolean  containsconstraintviolation(     set<constraintviolation<t>> violations, class<?> constraint) {      (constraintviolation<?> violation : violations) {         constraintdescriptor<?> descriptor = violation.getconstraintdescriptor();             if (constraint.isassignablefrom(descriptor.getannotation().getclass()))                 return true;         }     return false; } 

which allows me tests like

asserttrue(validationutils.containsconstraintviolation(violations, notnull.class)); 

however, i'm sure going naive in long run , wondering if there's not other library or api i'm missing assist in unit testing constraints.

you have @ class org.hibernate.validator.test.util.testutil used hibernate validator's own tests , offers functionality testing expected constraint violations (amongst others there assertcorrectconstrainttypes() example).

just note, class not part of hibernate validator's public api, may best use ideas.

when comparing error messages sure have vm's locale correctly set. better match against localized messages loaded via correct resource bundle (org.hibernate.validator.validationmessages standard constraints in case of hibernate validator).


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -