How to set up unit tests for Android / Gradle

After you read the Android tutorial for testing with the android gradle plugin, I wanted to set up JUnit tests for my POJO that did not run using instrumental tests. The idea was that tests for code that is not dependent on Android should be very fast (and facilitate TDD).

Is there a standard way to configure the source and tasks in build.gradle for this? This is the main question, the secondary question is what is wrong with my attempt below ...

I am using Android Studio 0.4.2 and gradle 1.9, experimenting with a simple JUnit test class in a new test folder. Here is what I still have, but when I run "gradle testPojo", I get this result:

:android:assemble UP-TO-DATE :android:compileUnitTestJava UP-TO-DATE :android:processUnitTestResources UP-TO-DATE :android:unitTestClasses UP-TO-DATE :android:testPojo FAILED * What went wrong: Execution failed for task ':android:testPojo'. > failed to read class file /path/to/project/android-app/build/classes/unitTest/TestClass.class 

I checked that the class actually exists, so I am confused about why the task is not able to read the file.

Here is the build.gradle file:

 ... sourceSets { unitTest { java.srcDir file('src/test/java') resources.srcDir file('src/test/resources') } } dependencies { ... unitTestCompile 'junit:junit:4.11' } configurations { unitTestCompile.extendsFrom instrumentTestCompile unitTestRuntime.extendsFrom instrumentTestRuntime } task testPojo(type: Test, dependsOn: assemble){ description = "Run pojo unit tests (located in src/test/java...)." testClassesDir = sourceSets.unitTest.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.unitTest.compileClasspath += files(buildDir) sourceSets.unitTest.runtimeClasspath += files(buildDir) } classpath = sourceSets.unitTest.runtimeClasspath } check.dependsOn testPojo 
+6
source share
1 answer

I suggest you use robolectric , declare it as follows:

 classpath 'org.robolectric:robolectric-gradle-plugin:0.11.+' 

And then apply the plugin:

 apply plugin: 'robolectric' 
0
source

All Articles