getting gradle to execute JUnit Test (Android app, Android Studio)

getting gradle to execute JUnit Test (Android app, Android Studio)

I am currently working on an android app and lately switched from Eclipse to Android Studio (wasn't my idea;)). However I want to configure a jenkins server to run JUnit Tests and other tests on a regularly basis. To achieve this, I try to configure a gradle buidlfile. Here is my setup:
Directory structure:


The build.gradle file: (located in "src/build.gradle)
    apply plugin: 'android'

    sourceSets {
        unitTest {
            java.srcDir file('src/test/java/[appName]/app')

    android {
        compileSdkVersion 19
        buildToolsVersion '19.0.3'

        defaultConfig {
            minSdkVersion 14
            targetSdkVersion 19
            versionCode 1
            versionName "1.0"
        buildTypes {
            release {
                runProguard false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        sourceSets {

    task unitTest(type:Test) {
        testClassesDir = sourceSets.unitTest.output.classesDir
        classpath = sourceSets.unitTest.runtimeClasspath

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile ''
        compile ''
        compile ''

        unitTest 'junit:junit:4.10'

    package [appName].app;

    import android.test.InstrumentationTestCase;
    import junit.framework.Assert;

    public class MainActivityTest extends InstrumentationTestCase{

        public void testMain(){

and the most important piece, the error message:
    Error:(41, 0) Build script error, unsupported Gradle DSL method found: 'unitTest()'!

It is my first time working with gradle and Android Studio and I have really no clue what I am doing wrong. On the internet I only find people with similar problems, but no one with a solution which worked for me. I'd be really glad if you could point me in the right direction!


Solution 1:

The error message tell that there is no such property unitTest. Test dependency are declared with instrumentTest (old) or androidTest (New).

Android sdk comes already with a junit 3 dependency. So just remove that line

Solution 2:

Unit testing doesn’t appear to work out of the box in Android Studio. I have a working Gradle configuration that runs unit tests using Robolectric after some minor configurations.

See: Gradlectric

Also to specify a different test folder you need to instead use androidTest:

sourceSets {
        androidTest {