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