Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classpath trouble using JUnit with both Eclipse and Maven

In a JUnit test I'm using this code to load in a test-specific config file:

InputStream configFile = getClass().getResourceAsStream("config.xml");

When I run the test through eclipse, it requires the xml file to be in the same directory as the test file.

When I build the project with maven, it requires the xml to be in src/test/resources, so that it gets copied into target/test-classes.

How can I make them both work with just one file?

like image 206
Steve Avatar asked May 19 '10 12:05

Steve


1 Answers

Place the config.xml file in src/test/resources, and add src/test/resources as a source folder in Eclipse.

The other issue is how getResourceAsStream("config.xml") works with packages. If the class that's calling this is in the com.mycompany.whatever package, then getResourceAsStream is also expecting config.xml to be in the same path. However, this is the same path in the classpath not the file system. You can either place file in the same directory structure under src/test/resources - src/test/resources/com/mycompany/whatever/config.xml - or you can add a leading "/" to the path - this makes getResourceAsStream load the file from the base of the classpath - so if you change it to getResourceAsStream("/config.xml") you can just put the file in src/test/resources/config.xml

like image 184
Nate Avatar answered Oct 17 '22 09:10

Nate