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?
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 thecom.mycompany.whateverpackage, thengetResourceAsStreamis 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 makesgetResourceAsStreamload the file from the base of the classpath – so if you change it togetResourceAsStream("/config.xml")you can just put the file in src/test/resources/config.xml