开发者

Classpath trouble using JUnit with both Eclipse and Maven

开发者 https://www.devze.com 2022-12-30 16:31 出处:网络
In a JUnit test开发者_开发问答 I\'m using this code to load in a test-specific config file: InputStream configFile = getClass().getResourceAsStream(\"config.xml\");

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 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


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.


I know this is an old question, but I stumbled on it and found it odd that none of the above answers mention the Maven Eclipse Plugin. Run mvn eclipse:eclipse and it will add src/main/resources and src/test/resources and such to the "Java Build Path" in Eclipse for you.

It has a bunch of stuff you can configure from there too (if you need to deviate from the conventions, if you don't then it's already ready to go):

  • Maven Eclipse Plugin - eclipse:eclipse
  • Maven Eclipse Plugin - sourceIncludes/sourceExcludes

In general, if you're using Maven, don't manually change stuff in Eclipse. Never commit your .classpath/.project and instead just use the Maven Eclipse Plugin to generate those files (and or update them). That way you have ONE configuration source for your project, MAVEN, and not manual settings that you end up having to tell others to use and remember yourself and so on. If it's a Maven project: check it out of source control, run "mvn eclipse:eclipse" and it should work in Eclipse, if it doesn't your POM needs work.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消