Search code examples
androidunit-testingandroid-studiogradleandroid-resources

How to add resources to androidTest for android library in AndroidStudio


I made an androidLibrary project which contains some Volley request classes, and want to write a unit test for some of these requests.

I have done that like a hundred times, and it works somehow after several tries, but never on the first try.

If I try this via androidStudio

RightClick Project->New->Android Resource Directory

you can choose between sourceSets "main", "debug" and "release". There is no androidTest option.

If I try it manualy, adding the following folders [moduleName]/src/androidTest/res/raw and put a file inside (lets say image.jpg), I do not get the reference via R.raw.image. In fact I haven't access to R.raw in my Test at all.

I also tried a Build->rebuild project or Build->clean without success.

In other projects I have a my.app.namespace.R along a my.app.namespace.test.R which holds all test resources.

So my question is: What do I need to do in order to add a res folder to my androidTest, which is accessible via R.[folder].[resId]?

Am I missing a crucial step after adding the files (i.e. telling gradle explicitly about it)?

Because adding a tag like this in my build.gradle also doesn't seem to make any difference:

android {
    sourceSets {
        androidTest {
            java.srcDirs = ['src/androidTest/java']
            res.srcDirs = ['src/androidTest/res']
        }
    }
}

If it matters I am using:

  • Android Studio 3.1.2
  • gradle-wrapper 4.4
  • minSdkVersion 19
  • targetSdkVersion 27

Solution

  • I figured out what is going on with the help of the update of Michael Krussel Answer:

    Android Studio is not compiling the my.app.namespace.test package automatically. All you need to do is run the Test the first time, ignoring the errors AndroidStudio might present.

    After the first run you got access to the whole test namespace (including the *.test.R class)

    No additional gradle config (like sourceSets from above) are necessary!