Grails domain: allow null but not empty for string

Environment: Grails 2.3.8

I have a requirement that the user password be blank, but cannot be blank. Therefore, I define the domain as follows:

class User{
    ...
    String password
    static constraints = {
        ...
        password nullable:true, blank: false
    }
}

I wrote a block test for limitations:

void "password can be null but blank"() {
    when: "create a new user with password"
    def user = new User(password: password)
    then: "validate the user"
    user.validate() == result
    where:
    password    | result
    "hello"     | true
    ""          | false
    null        | true
}

"hello" and "null" are fine, but an empty string ("") fails: junit.framework.AssertionFailedError: The condition is not met:

user.validate() == result
|    |          |  |
|    true       |  false
|               false
app.SecUser : (unsaved)

    at app.UserSpec.password can be null but blank(UserSpec.groovy:24)
  • Is nullable to override space: false?
  • I know that I can use a special validator to fulfill the requirement, I'm curious if there is a better way?
  • Am I doing something wrong?
+4
source share
1 answer

. , , , , :

void "password can be null but blank"() {
    when: "create a new user with password"
    def user = new User()
    user.password = password

    then: "validate the user"
    user.validate() == result

    where:
    password    | result
    "hello"     | true
    ""          | false
    null        | true
}

, .

null, - :

import grails.test.mixin.TestFor
import grails.test.mixin.TestMixin
import grails.test.mixin.web.ControllerUnitTestMixin
import spock.lang.Specification

@TestFor(User)
@TestMixin(ControllerUnitTestMixin)
class UserSpec extends Specification {

    static doWithConfig(c) {
        c.grails.databinding.convertEmptyStringsToNull = false
    }

    void "password can be null but blank"() {
        when: "create a new user with password"
        def user = new User(password: password)

        then: "validate the user"
        user.validate() == result

        where:
        password | result
        "hello"  | true
        ""       | false
        null     | true
    }
}
+4

Source: https://habr.com/ru/post/1598073/


All Articles