Change sourceset for tests only

I am building an Android app and have created some unit test that require access to some Android string resources (those that are built at compile time via aapt2 and accessed via the R class). At the same time, I don’t want to have these strings bundled in the released Android app (or Android library).

I originally tried the following in my app’s gradle:

tasks.withType(Test) {
    android.sourceSets.main.res.srcDirs += 'src/test/res'

and had my test resources at src/test/res. Even though this made the resources available in unit tests, the resources were also available in the actual app (not only in the unit tests).

Then, I tried the following:

tasks.withType(Test).configureEach() {
    android.sourceSets.main.res.srcDirs += 'src/test/res'

Using the following, the resources were hidden from the main app. They were available in unit tests if I ran them manually using gradlew test. However, when the tests were run from within Android Studio, the resources were not found.

What is the correct way to have the resources available to unit test (even when ran from Android Studio)?

PS. I am note sure I understand why “configureEach” behaves differently to the other and why the main sourceset is affected in tasks that are not of type “test”.

1 Like