Grails 域 : allow null but no blank for a string

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

"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)
  • 是否可以为空覆盖空白:假?
  • 我知道我可以使用自定义验证器来实现要求,我很好奇有没有更好的方法?
  • 难道我做错了什么?
  • 最佳答案

    默认情况下,数据绑定(bind)器将空白字符串转换为 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
        }
    }
    

    关于Grails 域 : allow null but no blank for a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31436326/

    相关文章:

    grails - Grails-如何显示最后上传的图像?

    grails - 导致多对多关系错误

    hibernate - Grails 3 集成测试在保存实体时抛出 "No Session found for current thread" hibernate 异常

    grails - 日期范围验证groovy grails

    grails - Grails-包之间的一对多表关系

    grails - 在Grails中保存关联的域类

    grails - 是否可以破解spring-security-core插件@Secured批注,以能够引用提供给 Controller 的请求参数?

    grails - 如何在Grails中读取xml文件?

    grails - Grails-如果值是负数,则将值显示为0

    Grails 3 领域类索引 TTL 按环境