views:

140

answers:

2

I have created a minimal maven project with a single child module in eclipse helios.

In the src/test/resources folder I have put a single file "install.xml". In the folder src/test/java I have created a single package with a single class that does:

  @Test
  public void doit() throws Exception {
    URL url = this.getClass().getClassLoader().getResource("install.xml");
    System.out.println(url.getPath());

  }

but when I run the code as a junit 4 unit test I just get a NullPointerException. This has worked fine a million of times before. Any ideas?

I have followed this guide:

http://www.fuyun.org/2009/11/how-to-read-input-files-in-maven-junit/

but still get the same error.

+2  A: 

It should be getResource("/install.xml");

The resource names are relative to where the getClass() class resides, e.g. if your test is org/example/foo/MyTest.class then getResource("install.xml") will look in org/example/foo/install.xml.

If your install.xml is in src/test/resources, it's in the root of the classpath, hence you need to prepend the resource name with /.

Also, if it works only sometimes, then it might be because Eclipse has cleaned the output directory (e.g. target/test-classes) and the resource is simply missing from the runtime classpath. Verify that using the Navigator view of Eclipse instead of the Package explorer. If the files is missing, run the mvn package goal.

mhaller
I have also tried: this.getClass().getClassLoader().getResource("/install.xml"); does not help (All my other project that reads resources do not use the "/" prefix and they work fine). I have also tried to run mvn clean install (both from commandline and from eclipse) on the parent and child but still the same problem. When I check the child folder: target/test-classes in the navigator view its empty - guess this is bad.
tul
yes, that's bad. Post the part of your pom where you specified (if any) the <resources> tags. Perhaps you're doing some <include> or <exclude> in there? mvn install should definitely copy your resource files to the classes resp. test-classes folder. Are you using M2Eclipse?
mhaller
I have not touched any include/exclude statements. I found this: https://issues.sonatype.org/browse/MNGECLIPSE-823 which might deal with this issue. I have created a new project and it works again.
tul
A: 

I have now created a fresh project and it works as usual again. I have noticed that this works fine:

URL url = this.getClass().getClassLoader().getResource("install.xml");
System.out.println(url.getPath());

but this gives a nullpointer:

URL url2 = getClass().getResource("install_test.xml");
System.out.println(url2.getPath()); 

unless I do:

URL url2 = getClass().getResource("/install_test.xml");
System.out.println(url2.getPath()); 

Why is it necessary to prefix with "/" when not getting the classLoader (getClassLoader())?

tul