1

我有一个需要返回 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)
    }
}
4

1 回答 1

2

Seeing Jeff's response in another topic in the mail list I think that you cannot use SiteMesh dependent tags in unit tests.

Possible solutions are:

  • Mock your html, asserting that the generated JSON is correct;
  • Do an Integration Test to validate your layout and template, since in integration you have access to the full env.;
于 2013-08-27T13:34:28.543 回答