views:

186

answers:

3

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 is gets copied into the target/test-classes.

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

+1  A: 

Try adding the src/test/resources/ directory as a source folder in your Eclipse project. That way, it should be on the classpath when Eclipse tries to run your unit test.

Ophidian
A: 

if you just need it at test time, you can load it via the file system, the context here should be the same for both cases:

new FileInputStream(new File("target/test-classes/your.file"));

not pretty, but it works

seanizer
+1  A: 

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

Nate
That's it! The / was the problem.Thanks!
Steve