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.

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

    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.

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

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

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

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

    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.

    apply plugin: 'idea'
    
    idea {
        module {
            testOutputDir = file('build/test-classes/debug')
        }
    }