'Organize shared code between androidTest and test
I'm building an android component in the form of a gradle project. To test my components UI in several configurations with the espresso framework, I have a TestActivity
in the androidTest
source set, which I can instrument.
To clarify the file tree:
src/
androidTest/
java/my.package/
TestActivity.kt
...
res/layout/
my_test_activitity.xml
test/
java/my.package/
MyUnitTests.kt
Now I want to start using robolectric for some of my unit tests and also test my TestActivity
from there.
Interestingly, Android Studio doesn't complain when I setup Robolectric in MyUnitTests.kt
:
val activity = Robolectric.setupActivity(TestActivity::class.java) // no error
However, when I try to run the unit tests, gradle is presenting me with this error:
e: src/test/java/my.package/MyUnitTests.kt: Unresolved reference: TestActivity
My guess is that the test
source set does not have access to the androidTest
source set, even though Android Studio seems to think it has.
How can I fix this (make classes and resources in androidTest
accessible from test
)? Is this even the correct approach when sharing code between instrumentation tests and unit tests or is there a better way?
Solution 1:[1]
I often get around this by creating a src/commonTest/java sourceset and expose that to both the instrumentation tests and unit tests by adding the following to my gradle file:
android {
sourceSets {
String sharedTestDir = 'src/commonTest/java'
test {
java.srcDir sharedTestDir
}
androidTest {
java.srcDir sharedTestDir
}
}
}
Solution 2:[2]
The accepted solution works great for normal Gradle scripts. However, for anyone using the Gradle Kotlin DSL (*.kts files) this should do the trick.
sourceSets {
val sharedTestDir = "src/sharedTest/java"
getByName("test") {
java.srcDir(sharedTestDir)
}
getByName("androidTest") {
java.srcDirs(sharedTestDir)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jdonmoyer |
Solution 2 | Jonathan Persgarden |