Notes: Get Robolectric to Work on Android Studio (RC) With Gradle

Disclaimer

This is obviously not a how-to, this is just a post dumping my notes. This will serve as personal reminder, and if it benefits others then your welcome.

Test Environment

  • Oracle JDK 1.7.0u67
  • Android Studio 1.0.0 RC4
  • Gradle 2.2.1

Setup

  1. In your root build.gradle, define the additional repo under buildscript > repositories as well as in your allprojects > repositories blocks.

    1
    2
    3
    maven {
    url 'https://oss.sonatype.org/content/repositories/snapshots'
    }
  2. Add a classpath dependency to the robolectric-gradle-plugin under buildscript > dependencies blocks.

    1
    classpath 'org.robolectric:robolectric-gradle-plugin:0.14.+'
  3. Apply the plugin (after applying Android Gradle’s plugin) in your build.gradle of your target module.

    1
    apply plugin: 'robolectric'
  4. Define the test instrumentation runner in your android > defaultConfig-block.

    1
    testInstrumentationRunner "com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner"
  5. Define the path where all our tests are located under android-block.

    1
    2
    3
    4
    5
    sourceSets {
    androidTest {
    setRoot('src/androidTest')
    }
    }
  6. Define the robolectric-block in which to choose what to include and exclude.

    1
    2
    3
    4
    robolectric {
    include '**/*Test.class'
    exclude '**/espresso/**/*.class'
    }
  7. Define Android test dependencies under the dependencies-block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    androidTestCompile 'org.hamcrest:hamcrest-integration:1.1'
    androidTestCompile 'org.hamcrest:hamcrest-core:1.1'
    androidTestCompile 'org.hamcrest:hamcrest-library:1.1'
    androidTestCompile('junit:junit:4.11') {
    exclude module: 'hamcrest-core'
    }
    androidTestCompile('org.robolectric:robolectric:2.4') {
    exclude module: 'classworlds'
    exclude module: 'commons-logging'
    exclude module: 'httpclient'
    exclude module: 'maven-artifact'
    exclude module: 'maven-artifact-manager'
    exclude module: 'maven-error-diagnostics'
    exclude module: 'maven-model'
    exclude module: 'maven-project'
    exclude module: 'maven-settings'
    exclude module: 'plexus-container-default'
    exclude module: 'plexus-interpolation'
    exclude module: 'plexus-utils'
    exclude module: 'wagon-file'
    exclude module: 'wagon-http-lightweight'
    exclude module: 'wagon-provider-api'
    }
    androidTestCompile 'com.squareup:fest-android:1.0.+'
  8. Define the output folder for Android Studio.

    1
    2
    3
    4
    5
    6
    7
    apply plugin: 'idea'
    idea {
    module {
    testOutputDir = file('build/test-classes/debug')
    }
    }