16 December 2014

I like to use Groovy to write scripts to help me test parts of my application that require a little more set up than a normal unit test should allow (think a small-scale integration test). Often, these scripts take the form of client-based code that establishes a connection to a locally running instance of my application and verifies that certain operations produce the desired and expected results. Recently, I found myself in a situation where I wanted to test some Spring Framework-based code that uses Thymeleaf to generate HTML. I didn’t necessarily want to extact the code into a separate library just so I could functionally test it outside of my application. Instead, I decided to take the project’s JAR file (as the application is a Spring Boot application) and use it as a dependency in my Groovy script. This meant that I would need to find a way to set up the Spring Framework context, so that all of the required dependency injection would take place. This turned out to not be that difficult:

import com.test.ApplicationConfiguration

import org.springframework.context.annotation.AnnotationConfigApplicationContext


def activeProfile = 'test'

def ctx = new AnnotationConfigApplicationContext()



In the example above, the script creates an instance of the AnnotationConfigApplicationContext Spring Framework context, sets the active profile, registers my Java-based configuration class (from my application’s JAR) and refreshes the context. At this point, you can reference any and all beans created by the configuration:

def bean = ctx.getBean('myBean')

You can obviously use the other variants of the ApplicationContext interface to configure your context (e.g. XML, etc). In a future post, I will discuss how to leverage the Spring Boot YAML support from a Groovy script so that you can leverage your application’s configuration files when in your script.

comments powered by Disqus