In a project I want to use some sample JSON files from src/test/resources in my test classes. The project can be found on https://github.com/kamikat/moshi-jsonapi if you want to test it for yourself. The project setup looks like this:
And in my tests I load the resource files like this:
public static String readResource(String resourceName) {
Scanner scanner = new Scanner(TestResources.class.getResourceAsStream(resourceName), "UTF-8");
return scanner.useDelimiter("\\A").next();
}
public static String getPrivateSample() {
return readResource("/private.json");
}
So far, so good. To add the *.json files to my classpath, I needed to add this to the build.gradle file:
sourceSets {
test {
resources {
srcDir "resources"
includes["**/*.json"]
}
}
}
Now I can run ./gradlew test
, and all tests are green - great!
But: If I run the tests from IntelliJ (Android Studio 2.2 RC1), the following happens:
java.lang.NullPointerException: source
at java.util.Objects.requireNonNull(Objects.java:228)
at java.util.Scanner.<init>(Scanner.java:578)
at moe.banana.jsonapi2.TestResources.readResource(TestResources.java:8)
at moe.banana.jsonapi2.TestResources.getPrivateSampleSerialized(TestResources.java:17)
at moe.banana.jsonapi2.PrivateAndProtectedTest.serializePrivate(PrivateAndProtectedTest.java:58)
at [...]
The problem appears to be that the JSON files are not added to the classpath when the tests run from IntelliJ. I can fix this temporarily by adding the resources as a manual dependency in the project settings, but I am looking for an automated solution.
I already tried this, this and this, but nothing works. Some answers suggest it's a bug in IntelliJ, which is marked as 'fixed' - but still there is no suitable solution working for me.
Did anyone get his test resources working correctly?