Grails Domain:允许空值但不允许字符串为空

Grails Domain: allow null but no blank for a string

环境:Grails 2.3.8

我有一个要求,用户的密码可以为空,但不能为空。 所以我这样定义域:

class User{
    ...
    String password
    static constraints = {
        ...
        password nullable:true, blank: 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
}

"hello" 和 null 情况都可以,但空白字符串 ("") 失败: junit.framework.AssertionFailedError:条件不满足:

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

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

默认情况下,数据绑定器会将空白字符串转换为 null。如果这确实是您想要的,您可以将其配置为不发生,或者您可以像这样修复测试:

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