Tuesday, August 27, 2013

Using g.applyLayout in controller breaks unit test

Using g.applyLayout in controller breaks unit test

I've got a controller method that needs to return a JSON map, one of the
items inside of which is html from a template. I'm using code like
map['html'] = g.applyLayout(name: 'layoutName', g.render(template:
'template', model: [...])
...
render(map as JSON)
And I've got at Controller unit test that calls this method. However when
I run the test, I get the following exception:
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)
...
If I take out the g.applyLayout() and just use the g.render() the test
runs. What am I doing wrong?
Update
Here's my unit test class
@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)
}
}

No comments:

Post a Comment