我是 Groovy 和 Grails 的新手。由于空字符串被转换为 null,Spock 对要测试的域对象进行持久化测试失败。这是代码。
域对象,
class Todo {
String name
Date createdDate
String priority
String status
static constraints = {
priority blank: true
}
}
Spock 规范,
@TestFor(Todo)
class TodoSpec extends Specification {
void "test persist"() {
when:
new Todo(name: 't1', createdDate: new Date(), priority: "1", status: 'ok').save()
new Todo(name: 't2', createdDate: new Date(), priority: '', status: 'ok').save()
then:
Todo.list().size() == 2
}
}
grails test-app
的结果是Todo.list().size() == 2
| | |
| 1 false
[collab.todo.Todo : 1]
at collab.todo.TodoSpec.test persist(TodoSpec.groovy:18)
我找到了空字符串
''
在线new Todo(name: 't2', createdDate: new Date(), priority: '', status: 'ok')
转换为 null
通过调试。谷歌一段时间后,我看到 Grails 中有一个功能可以将 Web 表单中的空字符串转换为 null 以持久化,可以通过配置 grails.databinding.convertEmptyStringsToNull = false
禁用该功能。在 Config.groovy 中。但我不认为 Spock UT 是这种情况。我试过了,但它不像我想的那样工作。我想知道为什么将空字符串转换为 null 作为传递给构造函数的参数?提前致谢。
最佳答案
现在有点麻烦,但可以很容易地工作。以下测试通过 Grails 2.3.9...
一个域类:
// grails-app/domain/com/demo/Person.groovy
package com.demo
class Person {
String title
}
配置.groovy:
// grails-app/conf/Config.groovy
grails.databinding.convertEmptyStringsToNull = false
// ...
一个单元测试:
// test/unit/com/demo/PersonSpec.groovy
package com.demo
import grails.test.mixin.TestFor
import spock.lang.Specification
@TestFor(Person)
@TestMixin(grails.test.mixin.web.ControllerUnitTestMixin)
class PersonSpec extends Specification {
void "test empty string conversion"() {
when:
def p = new Person(title: '')
then:
p.title == ''
}
}
关键是将 ContollerUnitTestMixin 应用于测试用例,即使它不是真正测试 Controller 。见 https://jira.grails.org/browse/GRAILS-11136 .
我希望这有帮助。
关于unit-testing - 为什么将空字符串转换为 null 传递给 Grails 2.4.0 中域对象的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24207822/