Sunday, August 24, 2008

getResourceAsStream() depends on what you're calling it on...

In writing some unit tests I ran into something I didn't expect. I had a .properties file that I was using to state metadata. In this case, the full path to a file my "Class Unit Test" was creating.

It seems that calling getResourceAsStream() off of getClass() does not return the resource. It's unfortunately that the Class class has a getResourceAsStream() method if it's not going to actually work.

So...
InputStream input = getClass().getResourceAsStream("./test.properties")
returns null.

If you use ResourceBundle to fetch "test" - it works.

I thought that was odd. I made a mention to my friend and he suggested that I need to be asking the ClassLoader to fetch the resource, not the class.

So...
InputStream input = getClass().getClassLoader().getResourceAsStream("./test.properties")
returns the resource.

Now - I am executing this from a GroovyTestCase instance. I do not know the reason for this. But either way, it's frustrating.


2 comments:

John T said...

Thanks for this little post! Helped me out

mike said...

Got the same problem, thanks for the hint.