Groovy for Java Unit Testing

I listened to a great podcast the other day on “Groovy Programming for Java Guys“. It was a really good look into the groovy language and how it relates to Java software development. I’ve sent this to management to try and help them understand better this whole “Groovy” thing.

My team has been integrating groovy code into our legacy Java project slowly over the last little while. Recently I have added it into our build scripts so Groovy can live alongside Java as a first class citizen. More importantly, now Groovy can be used in our unit tests. The groovyc ant task allows for joint compiling of Java and Groovy sources. This task is available with the new Groovy 1.5 release at groovy.codehaus.org.

There are a lot of features that Groovy brings to unit testing Java code. A big one is using map coercion to create mock objects. Your Java code may use an interface or class that does some particular operation in production. You might not want to actually perform the operation in a unit test but verify that the operation was performed. Coercion allows us to create a mock object that acts as a particular class but has different functionality. For example, if you have a production class that sends an email:class Mailer {

<span style="font-family: courier new">public void sendEmail() {</span>

    <span style="font-family: courier new">// Email sending code&#8230;</span>

    <span style="font-family: courier new"></span>

    <span style="font-family: courier new">System.out.println(&#8220;email sent&#8221;);</span>

<span style="font-family: courier new">}</span>

}

You can simulate a Mailer by creating a map that maps method names to a closure. The as keyword coerces the map to act as the Mailer class.

def fakeMailClosure = {

<span style="font-family: courier new">println &#8220;fake email&#8221;</span>

}

def testObject = [sendEmail: fakeMailClosure] as Mailer

testObject.sendEmail()

Just a few lines of groovy can create dummy objects that can be used to do whatever you want in a test environment. The testObject can even be passed into Java code where it is treated as a real Mailer.