How to create test classes that can be used both in Android tests and in unit tests?

I often find that I duplicate the exact set of test classes, such as mocks or helpers, for Android /androidTest tests and unit tests /test when writing tests for an application module.

For example, I have some static functions that help me quickly configure mocks in /test/MockUtils.java However, I cannot reuse this helper class in any of my Android tests, because they do not use the same class path - /androidTest vs /test .

I was thinking of creating a new module that contains only test resources. However, this idea will not fly, because the Android Gradle plugin refuses to depend on the application module.

projectCommon allows an APK archive that is not supported as a compilation dependency.

Is there any other way to create test classes that can be reused in Android tests and unit tests?

+5
source share
3 answers

NOTE. This is a theoretical solution that I have not tried.

Step # 1: create the testSrc/ directory in your module for which you are trying to configure a common test code.

Step # 2: Put the generic code in this directory (with the appropriate subdirectories based on the Java package).

Step # 3: Add the following closure inside your android closure in the build.gradle file:

 sourceSets { androidTest { java.srcDirs <<= 'testSrc' } test { java.srcDirs <<= 'testSrc' } } 

What you need to do is tell Gradle for Android that testSrc is another source directory for Java code in the androidTest and test androidTest .

+6
source

Based on the CommonsWare solution and https://code.google.com/p/android/issues/detail?id=181391, the correct way to add an additional class path is to use += or <<= operators.

 sourceSets { androidTest { java.srcDirs <<= 'testSrc' } test { java.srcDirs += 'testSrc' } } 
+4
source

The solution described in the blog below helped me.

http://blog.danlew.net/2015/11/02/sharing-code-between-unit-tests-and-instrumentation-tests-on-android/

I put my general test code in src / sharedTest / java. Then I added the following code for build.gradle:

 <pre> android { sourceSets { String sharedTestDir = 'src/sharedTest/java' test { java.srcDir sharedTestDir } androidTest { java.srcDir sharedTestDir } } } </pre> 
0
source

All Articles