Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access file in JUnit test in Gradle environment

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?

like image 702
Niklas Avatar asked Nov 20 '14 18:11

Niklas


People also ask

How do I run a single test file in Gradle?

In versions of Gradle prior to 5, the test. single system property can be used to specify a single test. You can do gradle -Dtest. single=ClassUnderTestTest test if you want to test single class or use regexp like gradle -Dtest.

Does Gradle use JUnit?

Enabling the Gradle's Native JUnit 5 SupportEven though Gradle (version 4.6 or newer) has a native support for JUnit 5, this support isn't enabled by default. If we want to enable it, we have to ensure that the test task uses JUnit 5 instead of JUnit 4.


1 Answers

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)

like image 83
Niklas Avatar answered Sep 28 '22 08:09

Niklas