Search code examples
androidandroid-gradle-pluginandroid-testingrobolectric

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

  • 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
            }
        }
    }