开发者

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 stra开发者_StackOverflow中文版ight 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜