Friday 18 January 2013

Grails TagLib mocking collaborators returns with Cannot invoke method [method] on null object


If you find yourself testing a TagLib and the TagLib uses a service, and you want to mock out that service in your test, you will need to retrieve the taglib from the applicationContext, otherwise setting your mocked service wont' work.

Example that won't work:

@TestFor(WebTagLib)
class WebTagLibTests {

void testTealium() {
tagLib.springSecurityService = mockSpringSecurityService(userId)
tagLib.geoIpService = mockGeoIpService('CAN')

assert applyTemplate('') == 'Hello World'
}
...

Returned exception:

org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException: Error executing tag : Cannot invoke method isLoggedIn() on null object

Example that will work:

@TestFor(WebTagLib)
class WebTagLibTests {
private static def userId = '12345'

void testTealium() {
def tagLib = applicationContext.getBean(WebTagLib)
tagLib.springSecurityService = mockSpringSecurityService(userId)
tagLib.geoIpService = mockGeoIpService('CAN')

assert applyTemplate('') == 'Hello World'
}

...

No comments:

Post a Comment