1

Here is my project structure: I have an xml file that I need to use it with my junit test case, I don't know why I can not get this file.

Even I mark the directory as test directory resources with intellij and there is no way. enter image description here

Here is my method:

@Before
    public void init() throws Exception {

        xml = IOUtils.toString(
                this.getClass().getResourceAsStream("reponse.xml"),
                "UTF-8"
        );
        ......
    }

I'm getting always the same error trace:

java.lang.NullPointerException
        at java.io.Reader.<init>(Reader.java:78)
        at java.io.InputStreamReader.<init>(InputStreamReader.java:113)
        at org.apache.commons.io.IOUtils.copy(IOUtils.java:1906)
        at org.apache.commons.io.IOUtils.toString(IOUtils.java:778)
        at org.apache.commons.io.IOUtils.toString(IOUtils.java:803)
        at fr.gouv.crpcen.restitution.ParserServiceTest.init(ParserServiceTest.java:113)
Masoud Mokhtari
  • 2,390
  • 1
  • 17
  • 45
Feres.o
  • 283
  • 1
  • 4
  • 16

2 Answers2

1

You missed some small detail, without this thing it wouldn't work.

Here is fixed version:

@Before
public void init() throws Exception {

    xml = IOUtils.toString(
            this.getClass().getResourceAsStream("/response.xml"),
            "UTF-8"
    );
    ......
}

I checked it works like charming.

catch23
  • 17,519
  • 42
  • 144
  • 217
0

Try to change "reponse.xml" to "/reponse.xml"

kurt
  • 1,510
  • 2
  • 13
  • 23
  • When you use a relative path (not starting with a “/“) to load a resource, it loaded relative to the class from which getResourceAsStream() is invoked – kurt Feb 14 '18 at 13:44
  • so, it was a searching on the same level where my calss is created ( i.e the package java ? ) i mean when the path is without the "/" – Feres.o Feb 14 '18 at 13:47
  • @Feres.o : This question should shed some light about it : https://stackoverflow.com/questions/14739550/difference-between-getclass-getclassloader-getresource-and-getclass-getres – Arnaud Feb 14 '18 at 13:48