【问题标题】:Grails Domain: allow null but no blank for a stringGrails 域:允许字符串为空,但不允许为空
【发布时间】:2015-10-04 20:14:30
【问题描述】:

环境: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)
  • 是否可以为空覆盖空白:假?
  • 我知道我可以使用自定义验证器来实现需求,我很好奇有没有更好的方法?
  • 我做错了吗?

【问题讨论】:

  • 哪个版本的 grails?部分版本通过数据绑定将Blank改为null。
  • 我使用的是 Grails 2.3.8。正如@Jeff Scott Brown 的回答确实解决了我的问题。我认为您的方向也是正确的。所以你的意思是在其他版本中,我的问题不会有问题,对吧?
  • 在旧版本中并非如此。我不记得这是从什么时候开始的。但是,是的,我说的和 Jeff 说的一样。
  • 在 Grails 2.3 中引入了将空白字符串转换为 null 的功能。见grails.github.io/grails-doc/2.3.0/guide/…

标签: grails grails-domain-class


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-06-21
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 2019-06-21
    • 2016-01-25
    • 2016-11-08
    • 1970-01-01
    相关资源
    最近更新 更多