QuickTip: Testing Custom Constraints in Grails

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:

protected void setUp() {
   super.setUp()
   ConstrainedProperty.registerNewConstraint(PhoneNumberConstraint.NAME
                       , PhoneNumberConstraint.class)
}

ShriKant Vashishtha is an enterprise Agile Coach, IT strategist, trainer, thinker and hands-on geek. He is passionate towards enterprise Agile transformation, quality aspect of software development including TDD, refactoring, Continuous Delivery, DevOps and Test Automation. He can be reached at vashishtha_sk@yahoo.com.

Posted in Grails, QuickTip

Leave a Reply

Your email address will not be published. Required fields are marked *

*

CommentLuv badge

Welcome to Sampreshan
Technology Strategist, Speaker, Scrum/XP/Agile Trainer Coach and Trainer
Your interest areas
Follow

Get every new post on this blog delivered to your Inbox.

Join other followers: