Not sure how this is possible. I re-read up on getResourceAsStream and it\'s always returning null.
InputStream source = this.getClass().getResourceAsStream(
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)
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.
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()));
You need to put the copy of your resource file to the test resources, in my example it is font file:
Then call next from your jUnit test:
public static InputStream getFontAsStream() throws IOException {
return Thread.currentThread().getContextClassLoader()
.getResourceAsStream("fonts/" + "FreeSans.ttf");
}
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.
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!