fweigl
fweigl

Reputation: 22018

No ressources availbable when running unit test

There's a known bug in Android Studio where the app's ressources aren't available from within test classes.

The solution according to aforementioned thread is to put the following lines into the build.gradle:

task copyTestResources(type: Copy) {
    from "${projectDir}/src/test/resources"
    into "${buildDir}/classes/test"
}
processTestResources.dependsOn copyTestResources

but gradle says:

Error:(132, 0) Could not find property 'processTestResources' on project ':app'.

Where exactly do I have to put the line

processTestResources.dependsOn copyTestResources

within my build.gradle?

EDIT:

I didn't have apply plugin: 'java' in my build files yet. The problem is that in my app module's build gradle, I already have apply plugin: 'android' and trying to add the java plugin leads to

Error:The 'java' plugin has been applied, but it is not compatible with the Android plugins.

I tried puttin apply plugin: 'java' in the top level build file and then

task copyTestResources(type: Copy) {
    from "${projectDir}/app/src/test/resources"
    into "${buildDir}/classes/test"
}

Note that I added the modules directory to the from-line. This builds fine, but unit tests that need to access ressources still don't work.

Upvotes: 5

Views: 633

Answers (2)

Ostkontentitan
Ostkontentitan

Reputation: 7010

There is a nice workaround to put this to work.: https://github.com/nenick/AndroidStudioAndRobolectric/blob/master/app/build.workaround-missing-resource.gradle

With this you can drop your extra task just add the ".gradle" file i linked and apply it in your modules build.gradle.

apply from: 'build.workaround-missing-resource.gradle'

Make sure to put your assets into app/test/resources/ and reference them via their name only.

e.g.: this.getClass().getClassLoader().getResource("my-asset-file.json")

I found the solution in the ticket you linked.: https://code.google.com/p/android/issues/detail?id=64887

Upvotes: 0

Hanno
Hanno

Reputation: 563

I was unaware that you were using the android plugin, sorry. You're getting the error because the Android plugin defines a different set of build tasks compared to the Java plugin. So you need to pick a different build task to depend your copyTestResources task on, for example:

apply plugin: 'android'

// (...) more build logic

task copyTestResources() {
    from "${projectDir}/src/test/resources"
    into "${buildDir}/classes/test"
}
check.dependsOn copyTestResources

Also, your copyTestResources task can be a little simpler like so:

task copyTestResources() {
    from sourceSets.test.resources
    into sourceSets.test.output.classesDir
}

Upvotes: 3

Related Questions