Testing custom validator in grails unit test case

14 / Nov / 2010 by Vishal Sahu 1 comments

Hi,

In my recent grails project, i needed to write unit test cases for testing custom validators which i created in command objects. To test validators, there is a method provided by grails “mockForConstraintsTests()” for validating constraints on Domain as well as Command-Object fields.

Let us take a scenario where we needed to use command object for user registration form. There are various fields in the class which include fields password and confirmPassword also. Now i want to validate that the value of password and confirm password should be same before saving it to the database.

I created custom validator for this which looks like.

 
  password(nullable: false, blank: false, minSize: 6)
  confirmPassword(nullable: false, blank: false, validator: {val, obj ->
            obj.properties['password'] == val
 })

The unit test which i write for this is like :-

void testUserPasswordConstraints() {

        mockForConstraintsTests(UserCommandObject)
        UserCommandObject uco = new UserCommandObject()
        uco.password="abcde"
        uco.confirmPassword="xyz"
        uco.validate()
        assertNotNull(uco.errors["confirmPassword"])  
// Validation message for password and confirmPassword field do not match

 }

So, by using ‘mockForConstraintsTests()’ method we can easily write test cases for testing constraints and custom validators for domain as well as command-object fields.It helped me a lot.

Hope this helps.

Vishal Sahu
vishal@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (1 “Testing custom validator in grails unit test case”)

Leave a Reply

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