It’s important to have test cases for your domain constraints in Grails. Sometimes, when you don’t see the availability of some constraints as Grails plugins, you would like to create one for yourself.
Testing a constraint itself is pretty straightforward as it will be a normal Groovy code. However while testing your Domain object alongwith custom constraints, I found something missing as tests were not getting executed at all. After some time, I figured out that the custom constraint need to be registered with Grails which we generally do in Config.groovy file. As Config.groovy gets executed in Grails environment and not in Unit test environment, the test itself will not run.
If you register the constraint in the setup method of test, it will work fine.. For instance if you have a custom constraint called PhoneNumberConstraint and you want to test domain which uses it, here’s what you need to do:
[groovy]
protected void setUp() {
super.setUp()
ConstrainedProperty.registerNewConstraint(PhoneNumberConstraint.NAME
, PhoneNumberConstraint.class)
}
[/groovy]