How to specify a test path in Eclipse

I have an Eclipse project with the following directory structure:

MyProj >> src/main/java >> src/main/config >> src/test/java >> src/test/config 

Inside src/test/config I have a properties file called app.properties , full of properties that are used by both classes in src/main/java and src/test/java .

All the code that I use to search for the properties file looks like this:

 try { Properties props = new Properties(); props.load(new FileInputStream("app.properties")); someString = props.getProperty("app.title.color"); // etc. } catch(Exception exc) { // Handle exception... } 

However, when I run this, I get the following error (handled inside the catch clause above):

java.io.FileNotFoundException: app.properties (the system cannot find the specified file)

But when I move the app.properties file to my project root (at the same level as, say, src/main/java ) and re-run the code, it works fine.

Obviously, this is a class problem. If I go to Build Path >> Configure Build Path >> Source , I see that src/test/config is actually the source folder in the build path. This may not mean it is also on the way to class !!!

How to configure Eclipse to search for src/test/config in the class path so that I can place my properties file there, but still have it available at runtime (when doing unit tests)?

Thanks in advance!

+4
source share
3 answers

The right way to do this (which ensures that your code continues to work if it is ever put in the JAR) is to add src/test/config to the classpath of your project and load the resources using the getResourceAsStream() method of the ClassLoader . eg.

 Thread.currentThread().getContextClassLoader().getResourceAsStream("app.properties") 
+3
source

This is not exactly a class problem (because you are not loading the class here!) - the problem is that your code is loading the file relative to the current working directory, which is your project root by default. FileInputStream does not know what classpath is - it just uploads files!

You can specify the path to the file:

 props.load(new FileInputStream("src/test/config/app.properties")); 

although it would be better to specify the configuration directory as a system property on the command line (or the Eclipse startup profile):

 -Dconfig.dir="src/test/config/" 

and then upload the files relative to this directory, for example:

 public static final String CONFIG_DIR = System.getProperty("config.dir"); props.load(new FileInputStream(CONFIG_DIR+"app.properties")); 
+2
source

Folders are merged, but you must access the properties file in different ways, as a resource relative to a class:

  InputStream is = YourClassName.class.getResourceAsStream("/app.properties"); 

Pay attention to "/".

0
source

Source: https://habr.com/ru/post/1394082/


All Articles