Sharing code between unit tests and instrumentation tests on Android

Suppose you've got an Android application with a bunch of tests. Some of them are unit tests (located in src/test). The rest are instrumentation tests (located in src/androidTest).

Here's the dilemma: you've got some utility code that you'd like all of your tests to share but src/test can't use code from src/androidTest and vice versa. You could put that code into src/main but you want to avoid shipping test code. How else do you share the code between the tests?

The solution I've come up with is to leverage source sets to define common code. First, I put my shared test code into src/sharedTest/java1 . Then I added the following code to build.gradle:

android {  
  sourceSets {
    String sharedTestDir = 'src/sharedTest/java'
    test {
      java.srcDir sharedTestDir
    }
    androidTest {
      java.srcDir sharedTestDir
    }
  }
}

What it's doing above is adding my shared code directory to both the test and androidTest source sets. Now, in addition to their default Java sources, they'll also include the shared code.

VoilĂ ! Now both test and androidTest can share utility code.


1 There's no particular reason the folder is called sharedTest. It could be anything.