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