Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read resource file from unit test?

I have a Java-only module in my Android project. In that project I want to have a unit test that reads the contents from a local json file that is stored in the resources folder. Android Studio changes the icon of the resources folder, so I'd think it recognises it as the resources folder.

How I'm reading:

String json = Files.lines(Paths.get("file.json"))
                .parallel()
                .collect(Collectors.joining());

folder structure:

+project
  +app (android)
  +module (java only)
    +src
      +main
        +java
          +package
            -the java file
        +resources
            -file.json

My question is how can I read the file?

updated below

URL resource1 = getClass().getResource("file.json");
URL resource2 = getClass().getClassLoader().getResource("file.json");
URL resource3 = Thread.currentThread().getContextClassLoader().getResource("file.json");
URL resource4 = ClassLoader.getSystemClassLoader().getResource("file.json");

All these are null. I've copied the json file to resources/same.package.structure too, but to no success.

like image 464
Rule Avatar asked Jul 09 '17 08:07

Rule


1 Answers

Don't need to do all this complicated stuff with ClassLoaders. You have access to test/resources directory from you /test/* classes.

enter image description here

enter image description here

UPD This is how to deserialize file using its path using SimpleXML. So here source method param is your path to resource file

enter image description here

like image 148
Anton Kazakov Avatar answered Sep 17 '22 23:09

Anton Kazakov