Aiden Zhao
Aiden Zhao

Reputation: 574

Grails Domain: allow null but no blank for a string

Environment: Grails 2.3.8

I have a requirement that the user's password could null but can't be blank. So I define the domain like this:

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

I wrote a unit-test for the constraints:

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
}

The "hello" and null cases are fine, but the blank string("") fails: junit.framework.AssertionFailedError: Condition not satisfied:

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

    at app.UserSpec.password can be null but blank(UserSpec.groovy:24)

Upvotes: 4

Views: 1012

Answers (1)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27255

The data binder by default converts blank strings to null. You could configure that to not happen if that is really what you want, or you could fix your test like this:

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
}

I hope that helps.

EDIT

If you want to disable the conversion of empty strings to null then you could do something like this:

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
    }
}

Upvotes: 4

Related Questions