junit testing with gradle for an android project

ligi picture ligi · Jun 20, 2013 · Viewed 25.5k times · Source

I am trying to get tests ( junit and robolectric ) working in an Android project but am totally stuck. My main problem is that all testing I found with gradle somehow pull in the java plugin and then I get this error:

The 'java' plugin has been applied, but it is not compatible with the Android plugins.

The only way out I see at the moment is to split into test and app project - but I would like to avoid that. Any examples/hints would be highly appreciated!

In the official documentation there is no mention of unit-testing - only Instrumentation-Tests - but I want unit-tests to get results fast.

Answer

newfivefour picture newfivefour · Jul 2, 2013

You don't need the Java plugin, since the Android will take care of what you need mostly, from what I've seen so far.

I managed to get my Robolectric and junit tests running via this man's blog: http://tryge.com/2013/02/28/android-gradle-build/

My build.gradle file looks like this (where my test files are in the {projectdir}/test directory.

...
// Unit tests

sourceSets {
        unitTest {
                java.srcDir file('test')
                resources.srcDir file('test/resources')
        }
}

dependencies {
        unitTestCompile files("$project.buildDir/classes/debug")
        unitTestCompile 'junit:junit:4.11'
        unitTestCompile 'org.robolectric:robolectric:2.1.1'
        unitTestCompile 'com.google.android:android:4.0.1.2'
}

configurations {
        unitTestCompile.extendsFrom runtime
        unitTestRuntime.extendsFrom unitTestCompile
}

task unitTest(type:Test, dependsOn: assemble) {
        description = "run unit tests"
        testClassesDir = project.sourceSets.unitTest.output.classesDir
        classpath = project.sourceSets.unitTest.runtimeClasspath
}

build.dependsOn unitTest