November 3, 2010

Gradle Goodness: Create JAR Artifact with Test Code for Java Project

Today, during my Gradle session, someone asked how to create a JAR file with the compiled test classes and test resources. I couldn't get the task syntax right at that moment, so when I was at home I had to find out how we can create that JAR file. And it turned out to be very simple:

apply plugin: 'java'

task testJar(type: Jar) {
    classifier = 'tests'
    from sourceSets.test.classes

The magic is in the from method where we use sourceSets.test.classes. Because we use sourceSets.test.classes Gradle knows the task testClasses needs to be executed first before the JAR file can be created. And of course the assemble task will pick up this new task of type Jar automatically.

When we run the build we get the following output:

$ gradle assemble