Why can't I access src / test / resources in a Junit test run with Maven?

I am having problems running the following code:

configService.setMainConfig("src/test/resources/MainConfig.xml"); 

From the Junit @Before Method.

Is Maven creating her target folder?

+42
java junit4 mockito
Sep 30 '11 at 16:29
source share
2 answers

Access MainConfig.xml directly. The contents of the src/test/resources directory are placed at the root of your CLASSPATH.

More precisely: the contents of src/test/resources copied to target/test-classes , so if you have the following project structure:

 . └── src └── test ├── java │  └── foo │  └── C.java └── resources ├── a.xml └── foo └── b.xml 

This will result in the following CLASSPATH test content:

  • /foo/C.class
  • /a.xml
  • /foo/b.xml

To access files from a Java source, use getClass().getResource("/MainConfig.xml").getFile() .

+63
Sep 30 '11 at 16:37
source share

I think setMainConfig expects the path to the resource that will be loaded using the ClassLoader, not the relative path to the file. This will help if you contacted the javadoc of this mysterious configService.setMainConfig method.

If my assumption is correct, then the path should only be MainConfig.xml. Mave copies the contents of src/test/resources to the target/test-classes (IIRC) folder. And this folder of test classes is on the way to the unit test class.

+2
Sep 30 '11 at 16:38
source share



All Articles