Robolectric in gradle

‹ Shared variables in Gradle's buildscript block | Using a Cisco compatible (vpnc) VPN from the command line in Linux ›

Robolectric is a unit test framework that allows you to test Android code in a normal JVM without an emulator. There are several versions of gradle plugins that are supposed to allow you to run robolectric tests in a gradle project, but none worked out of the box for me. Instead, this approach did:

sourceSets {
   robolectricTest {
      java.srcDir file('src/robolectricTest/java')
      resources.srcDir file('src/robolectricTest/res')
   }
}

dependencies {
   robolectricTestCompile 'junit:junit:4.11'
   robolectricTestCompile 'com.google.android:android:4.1.1.4'
   robolectricTestCompile "org.robolectric:robolectric:2.3"
}

task robolectricCheck(type: Test, dependsOn: assemble) {
   testClassesDir = sourceSets.robolectricTest.output.classesDir
   android.sourceSets.main.java.srcDirs.each { dir ->
      def buildDir = dir.getAbsolutePath().split('/')
      buildDir = (buildDir[0..(buildDir.length - 4)]
         + ['build', 'classes', 'debug']).join('/')
      sourceSets.robolectricTest.compileClasspath += files(buildDir)
      sourceSets.robolectricTest.runtimeClasspath += files(buildDir)
   }
   classpath = sourceSets.robolectricTest.runtimeClasspath
}

check.dependsOn robolectricCheck

configurations {
   robolectricTestCompile {
      extendsFrom compile
   }
}

Subscribe to All Posts - Wesley Tanaka