Reputation: 25391
Right now I have got a Java library which has a test class. In that class I want to access some files located on my hard disk.
The build.gradle looks like this:
apply plugin: 'java'
dependencies {
testCompile 'junit:junit:4.11'
}
My file is under java_lib/src/test/assets/file.xml
and the Java class is under java_lib/src/test/java/<package_name>.java
Therefore I execute
final InputStream resourceAsStream = this.getClass().getResourceAsStream("assets/file.xml");
Unfortunately I get null back. What am I doing wrong?
Upvotes: 21
Views: 23931
Reputation: 3732
This worked for me (3 years later, gradle 4.10)
subprojects {
junitPlatformTest.dependsOn processTestResources
}
Upvotes: 0
Reputation: 287
Thanks for pointing out the Google issue I've been looking all day for this...
In "Android Studio 1.1 RC 1" (gradle build tool 1.1.0-rc1) there is no need to add the work around to the gradle file, but your you have to execute the test from the gradle task menu (or command prompt)!
Upvotes: 0
Reputation: 25391
To get thing rolling you need to add the following to the gradle file:
task copyTestResources(type: Copy) {
from "${projectDir}/src/test/resources"
into "${buildDir}/classes/test"
}
processTestResources.dependsOn copyTestResources
What it basically does is copying all the files in the src/test/resource
directory to build/classes/test
, since this.getClass().getClassLoader().getResourceAsStream(".")
points to build/classes/test
.
The issue is already known to Google and they want to fix it in Android Studio 1.2 (since they need IntelliJ14 for that and it seems like it will be included in Android Studio 1.2)
Upvotes: 22
Reputation: 16833
In build.gradle
, add this :
sourceSets.test {
resources.srcDirs = ["src/test"]
}
In your code, access your resource like this :
getClass().getClassLoader().getResourceAsStream("assets/file.xml"));
Works for me.
Upvotes: 5
Reputation: 4905
Try placing file.xml
under src/test/resources
and use this.getClass().getResourceAsStream("file.xml")
(without the folder prefix)
The problem appears to be that the assets
folder is not part of the test runtime classpath, hence this.getClass().getResourceAsStream("assets/file.xml")
wouldn't be able to resolve the path as you expected.
By default, the test resources folder in a Gradle java project is src/test/resources
(same as a Maven java project). You can override it to assets
folder if you wish by adding this in the project's build.gradle
file:
sourceSets.test {
resources.srcDirs = ["src/test/assets"]
}
Upvotes: 10