Gradle, JUnit and AspectJ

I’m a believer in TDD, particularly when I’m writing challenging code. Recently I needed to write some Java annotations that acted as aspects around the methods they annotated.  But testing it proved to be a challenge. Try as I might, I could not get the AspectJ plugin to weave the aspects into the test code.  The weaving occurred on the main source but not the tests.

So here’s how I worked around it. Yes, my testing affected my implementation, which is a bad thing, but I think you’ll agree the impact was very minimal and the benefits where worth it.

I added a package “examples” to my source. In that package I put examples of each of the annotations working on example classes. My tests used those examples to test against. Then I made sure that that package was excluded from my resultant jar file.  Voila.

The relevant parts of my gradle.build is here:

buildscript {
    repositories {
        maven {
         url "https://maven.eveoh.nl/content/repositories/releases"
        }
    }
    dependencies {
        classpath "nl.eveoh:gradle-aspectj:1.6"
    }
}

project.ext {
    aspectjVersion = "1.8.7"
}

apply plugin: "aspectj"

jar {
    dependsOn classes
    from sourceSets.main.output
    exclude("**/examples") // Exclude the examples needed for tests
}

task javadocJar(type: Jar, dependsOn: javadoc) {
    from javadoc.destinationDir
    exclude("**/examples") // Exclude the examples needed for tests
    classifier = "javadoc"
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s