Loading a properties file in JUnit @BeforeClass

I am trying to load sample.properties from my class path during the execution of the JUnit test, and it cannot find the file in the class path. If I write the main Java class, I can just upload the file. I am using the following ant task to execute my JUnit.

public class Testing { @BeforeClass public static void setUpBeforeClass() throws Exception { Properties props = new Properties(); InputStream fileIn = props_.getClass().getResourceAsStream("/sample.properties"); **props.load(fileIn);** } } 

JUnit:

 <path id="compile.classpath"> <pathelement location="${build.classes.dir}"/> </path> <target name="test" depends="compile"> <junit haltonfailure="true"> <classpath refid="compile.classpath"/> <formatter type="plain" usefile="false"/> <test name="${test.suite}"/> </junit> </target> <target name="compile"> <javac srcdir="${src.dir}" includeantruntime="false" destdir="${build.classes.dir}" debug="true" debuglevel="lines,vars,source"> <classpath refid="compile.classpath"/> </javac> <copy todir="${build.classes.dir}"> <fileset dir="${src.dir}/resources" includes="**/*.sql,**/*.properties" /> </copy> </target> 

Output:

 [junit] Tests run: 0, Failures: 0, Errors: 1, Time elapsed: 0.104 sec [junit] [junit] Testcase: com.example.tests.Testing took 0 sec [junit] Caused an ERROR [junit] null [junit] java.lang.NullPointerException [junit] at java.util.Properties$LineReader.readLine(Properties.java:418) [junit] at java.util.Properties.load0(Properties.java:337) [junit] at java.util.Properties.load(Properties.java:325) [junit] at com.example.tests.Testing.setUpBeforeClass(Testing.java:48) [junit] 
+9
java junit ant
Apr 02 2018-12-12T00:
source share
1 answer

You need to add ${build.classes.dir} to compile.classpath .

Update . Based on the posts in the comments, it turned out that the classpath not a problem. Instead, the wrong classloader was used.

Class.getReasourceAsStream() looks at the resource path based on the class loader onto which the class was loaded. As it turned out, the Properties class was loaded by a different class loader than the Testing class, and the path to the resource was incorrect with respect to this classloader class path. The solution was to use Testing.class.getReasourceAsStream(...) instead of Properties.class.getResourceAsStream(...) .

+9
Apr 2 2018-12-12T00:
source share



All Articles