Wednesday, 4 January 2012

Taglib dependencies in Grails 2 unit tests

I'll essentially be reposting information that I found at Ad-Hockery (an excellent blog, by the way), but it was an annoying issue that took me some time to get working, so it's worth reposting.

Given a Grails controller as such:


class SomeController {
def something

def index() {
render something.method()
}
}


And its test:


import grails.test.mixin.*

@TestFor(SomeController)
class SomeControllerTests {

void testIndex() {
// given
controller.something = [method: { "hello!" }]

// when
controller.index()

// then
assert response.text == "hello!"
}
}


All works fine. So, given a very similar situation for a taglib:


class SomeTagLib {
static namespace = "blargh"
def something

def index = { attrs, body ->
out << something.method()
}
}

// ------

import grails.test.mixin.*

@TestFor(SomeTagLib)
class SomeTagLibTests {

void testIndex() {
// given
tagLib.something = [method: { "hello!" }]

// when
def output = applyTemplate("<blargh:index />")

// then
assert output == "hello!"
}
}


This would not work at - it was throwing a NullPointerException in the taglib itself, indicating my 'service' had not actually been wired in correctly.

Thanks to the blog post over at Ad-Hockery, I got this to work in the end by modifying my test as such:


import grails.test.mixin.*
import org.junit.Before;

@TestFor(SomeTagLib)
class SomeTagLibTests {

SomeTagLib tagLib

@Before
void setUp() {
tagLib = applicationContext.getBean(SomeTagLib)
}

void testIndex() {
// given
tagLib.something = [method: { "hello!" }]

// when
def output = applyTemplate("<<blargh:index />")

// then
assert output == "hello!"
}
}


I'm unsure about submitting a JIRA report for this as it may be expected behaviour; personally I'd expect the taglib tests to work as the controller ones do. hmm.

No comments: