我正在为将域类呈现为 JSON 响应的 Grails 控制器编写单元测试:
class MyController {
def find = {
def domainInst = MyDomainClass.get(params.id)
render ([data: domainInst] as JSON)
}
}
单元测试扩展了 ControllerUnitTestCase 并为域对象提供了一个模拟:
class MyControllerTests extends ControllerUnitTestCase {
@Before
void setUp() {
super.setUp()
mockDomain(MyDomainClass, [new MyDomainClass(id: 7)])
}
@Test
void testFind() {
def inst = MyDomainClass.get(7)
controller.params.id = inst.id
controller.find()
assert(controller.response.json.data.id == inst.id)
}
这一切似乎都运行良好,除了 JSON 渲染,它吐出一个讨厌的堆栈跟踪:
| Failure: testFind(MyControllerTests)
| org.apache.commons.lang.UnhandledException:
org.codehaus.groovy.grails.web.converters.exceptions.ConverterException: Error converting Bean with class MyDomainClass
Caused by: org.codehaus.groovy.grails.web.converters.exceptions.ConverterException: Error converting Bean with class MyDomainClass
at grails.converters.JSON.value(JSON.java:199)
at grails.converters.JSON.convertAnother(JSON.java:162)
at grails.converters.JSON.value(JSON.java:199)
at grails.converters.JSON.render(JSON.java:134)
... 5 more
Caused by: java.lang.reflect.InvocationTargetException
... 9 more
Caused by: groovy.lang.MissingMethodException: No signature of method: MyDomainClass.isAttached() is applicable for argument types: () values: []
Possible solutions: isAttached(), attach()
... 9 more
将返回更改为 Map 而不是域类有效:
render ([data: [id: domainInst.id]] as JSON)
是什么导致 JSON 编组器在域类上死掉?它可以在正常环境中工作,但不能在模拟测试环境中。有没有办法使这个测试工作?