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 {
public void sendEmail() {
// Email sending code…

System.out.println(“email sent”);
}
}

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 = {
println “fake email”
}
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.

One thought on “Groovy for Java Unit Testing”

Comments are closed.