Search code examples
androidtestingandroid-studiogradleandroid-testing

Sharing code between Android Instrumentation Tests and Unit Tests in Android Studio


It is possible to share code between this two test modes in Android Studio? I have a set of Mock Utils class's that I need to access in both of the test modes.


Solution

  • Finally I found the solution (workaround) thanks to a blog post from Dan Lew (http://blog.danlew.net/2015/11/02/sharing-code-between-unit-tests-and-instrumentation-tests-on-android/).

    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 .

    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.

    Edit (20022-08-15): This no longer works, for a discussion of why, and the (now) recommneded way to achieve sharing of code, see this question and the accepted answer: Shared srcDirs between test and androidTest, unresolved references after upgrade to Android Studio Chipmunk (IntelliJ 2021.2.1)