Reputation: 14584
I often find myself duplicating the exact same set of test classes such as mocks or helpers for both Android tests /androidTest
and unit tests /test
when writing tests for an application module.
For example, I have some static functions that help me set up mocks quickly in /test/MockUtils.java
However, I cannot reuse this helper class in any of my Android tests because they do not share the same class path - /androidTest
vs /test
.
I've thought of creating a new module that only contains test resources. However, this idea won't fly because the Android Gradle plugin refuses to depend on an app module.
project testCommon resolves to an APK archive which is not supported as a compilation dependency.
Is there any other way to create test classes that could be reused in both Android tests and unit tests?
Upvotes: 7
Views: 2320
Reputation: 155
The best approach for now is to create shared gradle-module as described in this article.
Just create a module (e.g. sharedTest
) and use it as testImplementation
and androidTestImplementation
.
The solution with shared sources folder is not working in the modern versions of Android Studio.
Upvotes: 0
Reputation: 5307
The solution described in the blog below helped me.
I put my shared test code into src/sharedTest/java . Then I added the following code to build.gradle:
<pre>
android {
sourceSets {
String sharedTestDir = 'src/sharedTest/java'
test {
java.srcDir sharedTestDir
}
androidTest {
java.srcDir sharedTestDir
}
}
}
</pre>
Upvotes: 0
Reputation: 1007554
NOTE: This is a theorized solution, one that I have not tried.
Step #1: Create a testSrc/
directory in your module for which you are trying to set up the shared testing code.
Step #2: Put the shared code in that directory (with appropriate subdirectories based on Java package).
Step #3: Add the following closure inside your android
closure in your module's build.gradle
file:
sourceSets {
androidTest {
java.srcDirs <<= 'testSrc'
}
test {
java.srcDirs <<= 'testSrc'
}
}
What this should do is tell Gradle for Android that testSrc
is another source directory for Java code in the androidTest
and test
sourcesets.
Upvotes: 6
Reputation: 14584
Based on CommonsWare's solution and https://code.google.com/p/android/issues/detail?id=181391, the correct way to add an additional class path is to use the +=
or <<=
operators.
sourceSets {
androidTest {
java.srcDirs <<= 'testSrc'
}
test {
java.srcDirs += 'testSrc'
}
}
Upvotes: 3