Unit testing a custom validator of a team object with a dependency

I have a command object to register a user, and I want to check how old the user is. This command object is service dependent. How can I check a custom validator for my dateOfBirth property? What it now looks like right from the 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 arises: how can I mock the 'obj' validator close parameter?

+5
source share
1 answer

- GrailsUnitTestCase.mockForConstraintsTests. , validate(), .

, unit test. blank , 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']
    }
}

, unit test ( ), , , cmd.someservice.

+8

All Articles