Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 888
Sandro Machado Avatar asked Jun 03 '15 18:06

Sandro Machado


People also ask

What are Android instrumentation tests?

Instrumented tests are tests that run on physical devices and emulators, and they can take advantage of the Android framework APIs and supporting APIs, such as AndroidX Test.

What is Robolectric?

Robolectric is a framework that allows you to write unit tests and run them on a desktop JVM while still using Android API. Robolectric provides a JVM compliant version of the android. jar file.


2 Answers

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.

like image 172
Sandro Machado Avatar answered Sep 18 '22 11:09

Sandro Machado


For multiple modules project

sourceSets {
        test.java.srcDirs += ["${project(':module-name').projectDir}/src/sharedTest/java",
                              "src/test/java"]
    }
like image 36
takharsh Avatar answered Sep 20 '22 11:09

takharsh