Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing custom validator of command object with dependency

I have a command object for registering user, and I want to check how old is the user. This command object has a service dependency. How can I test custom validator for my dateOfBirth property? As it looks now is taken straight from documentation, here.

class RegisterUserCommand {

  def someService

  String username
  String password
  String password2
  String email
  Date dateOfBirth

  static constraints = {
    // other constraints
    dateOfBirth blank: false, validator: {val, obj ->
      return obj.someService.calculateAge(val) >= 18
    }
  }

So basically the question is: how can I mock 'obj' parameter of the validator closure?

like image 294
jjczopek Avatar asked Mar 26 '11 22:03

jjczopek


1 Answers

The easiest way to test validation on a command object is to use GrailsUnitTestCase.mockForConstraintsTests. A mock validate method will be applied to your command object, and you can just call validate() like you would outside of a test.

Here's an example of how you could write your unit test. The blank constraint isn't meaningful for dates, so I've changed it to nullable: false.

import grails.test.GrailsUnitTestCase

class RegisterUserCommandTests extends GrailsUnitTestCase {
    RegisterUserCommand cmd

    protected void setUp() {
        super.setUp()
        cmd = new RegisterUserCommand()
        mockForConstraintsTests RegisterUserCommand, [cmd]
    }

    void testConstraintsNull() {
        cmd.dateOfBirth = null
        cmd.someService = [calculateAge: { dob -> 18 }]
        def result = cmd.validate()
        assert result == false
        assert cmd.errors.getFieldErrors('dateOfBirth').code ==  ['nullable']
    }

    void testConstraintsCustom() {
        cmd.dateOfBirth = new Date()
        cmd.someService = [calculateAge: { dob -> 17 }]
        def result = cmd.validate()
        assert result == false
        assert cmd.errors.getFieldErrors('dateOfBirth').code == ['validator.invalid']
    }
}

Note that your service won't get injected in a unit test (it will in an integration test though), so you'll either need to mock it, as above, or create an instance and assign it to cmd.someservice.

like image 139
ataylor Avatar answered Nov 17 '22 13:11

ataylor