Junit + getResourceAsStream Returning Null
Asked Answered
C

15

59

Not sure how this is possible. I re-read up on getResourceAsStream and it's always returning null.

InputStream source = this.getClass().getResourceAsStream("test.xml");

Right next to test.java in the Finder (using OS X and Eclipse) is test.xml

I can open it in TextWrangler and view it as existing with data inside.

This is a Junit test if it makes any difference. I went and looked at existing Junit tests on our system and I'm using it in the exactly same manner as a working example (as in where the file is located and the code itself).

What small difference could there be preventing I assume getClass() from returning the right path?

Cards answered 8/3, 2011 at 20:37 Comment(0)
L
27

getResourceAsStream() is using the CLASSPATH, and as such it will load from wherever your classes are, not your source files.

I suspect you need to copy your XML to the same directory as your .class file.

Lineament answered 8/3, 2011 at 20:44 Comment(0)
A
36

It's not finding the resource on the classpath. If you are using junit and maven make sure the resources are copied on the target/test-classes by adding <include> file directive on <testResource> section

You can also find out the location of your class in the file system by using

this.getClass().getResource(".")

and checking to see if the resource is there

Agenesis answered 30/6, 2011 at 21:12 Comment(3)
System.out.println(MyClass.class.getResource(".").getPath());Negligent
System.out.println(this.getClass().getClassLoader().getResource(".").getPath());Instanter
Yeah this helped! I could see what the folder was where things were being compiled, then I searched through that folder on the command line to see where my resources was, and loaded it relative to that.... Thanks!Mahaffey
M
29

In case you are using Maven, add this part to your pom.xml

<build>
    <testResources>
        <testResource>
            <directory>${project.basedir}/src/test/resources</directory>
        </testResource>
    </testResources>
</build>

Your test.xml and other resource files must be located in src/test/resources

Moseley answered 26/3, 2015 at 13:45 Comment(1)
Does this copy src/main/resources to a location where test files can access them? This directory is the default for test resources already... so I'm not sure why it needs to be specified?Travers
L
27

getResourceAsStream() is using the CLASSPATH, and as such it will load from wherever your classes are, not your source files.

I suspect you need to copy your XML to the same directory as your .class file.

Lineament answered 8/3, 2011 at 20:44 Comment(0)
S
13

I always have problem with this method. Here are 2 links, which might be useful:

I always experiment with adding "/" at the beginning or "./".

From my experience the best method is using FileInputStream. There is only one thing to remember (while using FileInputStream with Eclipse), with default settings, your working directory is set to projects root. You can always check where is your current directory (and what relative paths you need)using this piece of code.

Splanchnic answered 8/3, 2011 at 21:12 Comment(1)
Like -> I always experiment with adding "/" at the beginning or "./".Humor
S
13

Assuming test.xml is located right under your test root source folder, do this:-

InputStream source = this.getClass().getClassLoader().getResourceAsStream("test.xml");
Shophar answered 8/3, 2011 at 21:51 Comment(0)
S
6

try using classloader

InputStream source = this.getClass().getClassLoader().getResourceAsStream("test.xml");
Stellastellar answered 2/3, 2020 at 11:0 Comment(2)
Prepending classpath: to the path was crucial for me, so "classpath:/test.xml"Reckford
Is this just a repeat of this existing answer?Rule
F
3

I spent lot of time in this problem and it was missing me the following configuration: Right-click on an eclipse project and select Properties -> Java Build Path -> Source and edit Included row and add *.properties (*.fileExtension)

Framboise answered 21/12, 2017 at 19:21 Comment(0)
K
2

Put test.xml in the src/main/resources (or src/test/resources).

File file = ResourceUtils.getFile("classpath:test.xml");
String test = new String(Files.readAllBytes(file.toPath()));
Kneehigh answered 23/10, 2019 at 5:49 Comment(0)
W
0

Try MyClass.getResourceAsStream().

Also try putting the test.xml in your classpath. For instance, in an Eclipse web project put text.xml in webcontent/WEB-INF/classes

Wineshop answered 8/3, 2011 at 21:10 Comment(0)
N
0

From Java API:

http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getSystemResource(java.lang.String)

Find a resource of the specified name from the search path used to load classes. This method locates the resource through the system class loader

So the syntax will for instance be: ClassLoader.getSystemResource("test.xml").toString();

Works like a charm!

Nuclide answered 12/6, 2013 at 9:10 Comment(0)
M
0

Seems there are a lot of possible causes to this and mine was not found here. I figured out that my tests were no longer being detected/run by maven and this baeldung post also provided a lot of possible causes. My problem ended up being that at some point I altered the wrong pom and set my packaging to pom.

The test-compile step was being skipped completely and no new resources were ending up in the classpath. So, check your target/test-classes directory and make sure that your tests are actually compiling in the first place.

Misestimate answered 5/10, 2022 at 17:48 Comment(0)
B
0

I got a Similar issue. The problem in my case was that getResourceAsStream() was working fine for the main Application code but giving Null in case of unit-test. The problem was that for the main Application code it was looking in the target/classes folder for the file but for the unit-test it was looking in the target/test-classes. I fixed the problem by adding my file in the test/resources folder.

Breath answered 13/10, 2022 at 18:48 Comment(0)
I
-1

Add the folder that your having your resource files in to the source folders of eclipse. Then the file should be automatically put in the bin directory.

Impious answered 9/2, 2012 at 0:21 Comment(0)
L
-1

You need to put the copy of your resource file to the test resources, in my example it is font file:

enter image description here

Then call next from your jUnit test:

 public static InputStream getFontAsStream() throws IOException {
        return Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("fonts/" + "FreeSans.ttf");
    }
Longlived answered 26/7, 2017 at 7:23 Comment(0)
T
-2

I had this problem with a Spring class. System.class.getResourceAsStream(...) worked in unit tests but not in Tomcat, Thread.currentThread().getContextClassLoader().getResourceAsStream(...) worked in Tomcat but not in unit tests.

Ulitimately I went with:

ClassUtils.getDefaultClassLoader()
    .getResourceAsStream("com/example/mail/templates/invoice-past-due.html"))

I also found that once I did it this way, I did not need to have the path starting with a slash.

Theophilus answered 11/11, 2016 at 23:12 Comment(1)
Where did you get ClassUtils from?Androgynous

© 2022 - 2024 — McMap. All rights reserved.