Reputation: 1334
I have a class method that reads resource file, but file can not be find when I'm trying to run this class with unit tests.
If I were to deploy application war or just run it from eclipse using maven, everything works just fine.
File locations (not sure if src/test/resources is needed, added it only after I encountered the problem, did not help though):
src/main/resources/
-> com
-> xxxx
-> xxxx_portal
-> web
-> server
-> servlet
-> reports -> Logo.png
src/test/resources/
-> com
-> xxxx
-> xxxx_portal
-> web
-> server
-> servlet
-> reports -> Logo.png
Relevant class code:
package com.xxxx.xxxx_portal.web.server.servlet.reports;
public class ModuleReports {
private static final String LOGO_IMAGE_PATH = "/com/xxxx/xxxx_portal/web/server/servlet/reports/Logo.png";
...
private static InputStream getLogoImage() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream is = classLoader.getResourceAsStream(LOGO_IMAGE_PATH); //Problem here, InputStream is null. It should not be null.
return is;
}
...
}
Upvotes: 0
Views: 875
Reputation: 44404
The argument to ClassLoader.getResourceAsStream must not start with a slash (/
). While you could just remove the initial slash from the value of ACDLABS_LOGO_IMAGE_PATH, you should use Class.getResourceAsStream rather than ClassLoader.getResourceAsStream:
private static InputStream getLogoImage() {
return ModuleReports.class.getResourceAsStream("ACDLogo.png");
}
Unlike ClassLoader.getResourceAsStream, the argument to Class.getResourceAsStream can start with a slash, but doesn’t need to. If it doesn’t, the string is assumed to point to a resource in the same package as the class on which it is invoked. All of this behavior is described in the documentation.
Upvotes: 1