Automatically compiling test cases using Gradle

Recently I’ve been doing a lot of refactoring on the Android app that I’m working on and most of the time a refactoring breaks one or many of the existing test cases. Sometimes there are tests that fail but mainly it’s simply that the test cases don’t compile after I’ve changed something. Most of the time I remember to run the test cases to make sure that nothing is broken. However, most of the time is not all the time. Sometimes I get angry mails from Jenkins telling me the build is broken.

I’ve realized that it would be better if I couldn’t avoid compiling the test cases when compiling the app, that way catching possible compile errors in the tests all the time. I’m using AndroidStudio and Gradle to build so what I want to do is to add a dependency in my build.gradle from the task assembleDebug to the task compileDebugTestJava. That’s a simple one-liner like this:

tasks.assembleDebug.dependsOn tasks.compileDebugTestJava

However, this fails with the message “Could not find property ‘compileDebugTestJava’ on task set”. This is because the task compileDebugTestJava is dynamically created. Turns out that we can solve it anyway. With a bit of help from this blog post we can write this:

tasks.whenTaskAdded { task ->
    if ( == 'compileDebugTestJava') {
        tasks.assembleDebug.dependsOn task

Now whenever a task get’s added, we check if the name of the task is the one we’re looking for. If it is, we add it as a dependency to the assembleDebug task.

Now, whenever I run my app from android studio or build it from gradle, it also compiles my test code. Hopefully, this will decrease the amount of angry mails I get from Jenkins.

This Post Has One Comment

  1. Lachlan

    I often make the main assemble/build task require actually running the whole test suite on top of simply compiling it. Then again, my suites run really fast so it’s not an overhead for me.

Leave a Reply