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

时间:2015-07-15 16:46:24

标签: grails grails-domain-class

环境: 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
}

"你好"和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)
  • 可空可覆盖空白:false?
  • 我知道我可以使用自定义验证器来实现要求,我很好奇有没有更好的方法?
  • 我做错了吗?

1 个答案:

答案 0 :(得分:4)

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

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