我有一个需要返回 JSON 映射的控制器方法,其中一个项目是来自模板的 html。我正在使用类似的代码
map['html'] = g.applyLayout(name: 'layoutName', g.render(template: 'template', model: [...])
...
render(map as JSON)
我已经在控制器单元测试中调用了这个方法。但是,当我运行测试时,出现以下异常:
java.lang.IllegalStateException: Cannot return Sitemesh factory it has not been set!
at org.springframework.util.Assert.state(Assert.java:384)
at org.codehaus.groovy.grails.web.sitemesh.FactoryHolder.getFactory(FactoryHolder.java:39)
at org.codehaus.groovy.grails.web.sitemesh.FactoryHolder$getFactory.call(Unknown Source)
...
如果我取出 g.applyLayout() 并只使用 g.render() 测试运行。我究竟做错了什么?
更新
这是我的单元测试课
@TestFor(ContactsController)
@Mock([Contact, User, Company])
class ContactsControllerTests {
@Test
void testSaveContact() {
defineBeans {
contactsManagerService(ContactsManagerService)
}
Company company = new Company(name: 'COMPANY 1')
company.save(validate: false)
Contact userContact = new Contact(name: 'user contact', email: 'foo@bar.com')
Contact companyContact = new Contact(name: 'company contact', email: 'foo2@bar.com')
userContact.save(validate: false)
companyContact.save(validate: false)
new User(name: 'user 1', password: 'foo', contact: userContact, company: company).save(validate: false, deepValidate: false)
controller.params.name = ''
controller.params.email = 'updated1@bar.com'
controller.saveContact(userContact.id)
assertNotNull(response.json.errors) // Name cannot be empty
response.reset()
controller.params.name = 'Updated Name'
controller.params.email = 'updated1@bar.com'
controller.saveContact(userContact.id)
assertTrue(response.json.success)
Contact contact = Contact.read(userContact.id)
assertEquals('Updated Name', contact.name)
assertEquals('foo@bar.com', contact.email)
}
}