我有一个 Controller 方法,需要返回一个JSON映射,其中的一项是模板中的html。我正在使用类似的代码
map['html'] = g.applyLayout(name: 'layoutName', g.render(template: 'template', model: [...])
...
render(map as JSON)
我在 Controller 单元测试中调用了此方法。但是,当我运行测试时,出现以下异常:
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)
}
}
最佳答案
在邮件列表的另一个主题中看到Jeff's response,我认为您不能在单元测试中使用依赖SiteMesh的标记。
可能的解决方案是:
关于unit-testing - 在 Controller 中使用g.applyLayout破坏单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18465057/