Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organize shared code between androidTest and test [duplicate]

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?

like image 301
Georg Grab Avatar asked Nov 21 '25 05:11

Georg Grab


1 Answers

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
        }
    }
}
like image 130
jdonmoyer Avatar answered Nov 22 '25 19:11

jdonmoyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!