Since a plugin is a Grails application, you should add tests to your plugin project. Let's begin with opening a command window in the plugin project (jamon) and creating a test class:
grails create-integration-test JamonGrailsPlugin
Now we edit the class Grails created. We find this class in jamon\test\integration\JamonGrailsPluginTests.groovy.
First we see Grails creates a class that extends GrailsUnitTestCase. Since this is an integration test, we'll change it to extend GroovyTestCase instead. Let's add a few handy imports as well:
import grails.test.*
import org.codehaus.groovy.grails.commons.ApplicationHolder
import org.codehaus.groovy.grails.commons.GrailsApplication
import javax.sql.DataSource
class JamonGrailsPluginTests extends GroovyTestCase {
I'll add a couple variables for brevity sake:
def app = ApplicationHolder.application
def ctx = app.mainContext
Next we'll add the boiler plate setUp and tearDown methods. I like AgileDox naming so I'll override getName() as well:
protected void setUp() {
super.setUp()
}
protected void tearDown() {
super.tearDown()
}
public String getName() {
return super.getName().substring(4).replaceAll("([A-Z])", " \$1").toLowerCase();
}
This first test will be to verify the dataSources have been updated with the jamon proxy:
void testDataSourcesAreJamonEnabled() {
ctx.getBeanNamesForType(DataSource).each{ beanName ->
def bean = ctx.getBean( beanName )
assertEquals "com.jamonapi.proxy.JAMonDriver", bean.driverClassName
assert bean.url.startsWith("jdbc:jamon:")
assert bean.url.contains('jamonrealdriver=')
}
}
We make use of the Spring method getBeanNamesForType() to get all beans subclassed from DataSource, then simply test the attributes we attempted to set.
To verify that jamon is configured in the Spring context, we need a class in the plugin, such as a service class, to verify it is included in autoProxyCreatorBean. We can add a service by the grails command 'grails create-service jamonTest'. Of course we do not want the class added to our target applications, so we add the classname to the pluginExcludes variable in JamonGrailsPlugin:
def pluginExcludes = [
"grails-app/views/error.gsp",
"grails-app/services/JamonTestService.groovy"
]
Now we can code out test:
void testJamonHasSpringAop() {
assertNotNull ctx.getBean("jamonInterceptor")
def autoProxyCreatorBean = ctx.getBean("autoProxyCreator")
assertNotNull autoProxyCreatorBean
assertArrayEquals (["jamonTestService"].toArray(), autoProxyCreatorBean.beanNames.toArray())
}
The remaining tests can be coded in a similar fashion. It is a good idea to include tests for all the plugin behaviours as well as any bugs that creep up over time.
That is it for the JAMon series. Hope these articles saved you some time. Your comments are encouraged!