Maven: Unable to find resources in test cases?

November 9th, 2007 by  |  Published in Maven

Just right now, I was once again fighting the beast called Maven. This time, my JUnit tests failed with Maven although they used to work within in Eclipse. The test cases failed due to missing resources. I searched for these resources using the ClassLoader.getResource() mechanism which always worked just fine so far.

After some swearing and investigation I finally found the problem: In my code, I used ClassLoader.getSystemResource(...) to find a resource, which internally calls ClassLoader.getSystemClassloader(). However, with Maven’s Surefire plugin, the system classloader does neither contain target/classes nor target/test-classes in its classpath. Therefore, you have to make sure, that the classloader that loaded the test cases (and the tested classes) is used to get the resources.

Therefore, instead of

ClassLoader.getSystemResource(...)

always use

this.getClass().getClassLoader().getResource(...)

Problem solved!

Leave a Response