2012-04-02 66 views
9

我想在我的JUnit測試執行期間從我的類路徑加載sample.properties,並且它無法在類路徑中找到該文件。如果我寫一個Java Main類,我可以很好地加載文件。我正在使用下面的ant任務來執行我的JUnit。加載屬性文件在JUnit @BeforeClass

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> 

輸出:

[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

您需要添加${build.classes.dir}compile.classpath

更新:根據評論中的溝通,原來classpath不是問題所在。相反,使用了錯誤的類加載器。

Class.getReasourceAsStream()根據類加載的類加載器查找資源的路徑。事實證明Properties類是由不同於類Testing的類加載器加載的,並且與該類加載器的類路徑相關的資源路徑不正確。解決方案是使用Testing.class.getReasourceAsStream(...)而不是Properties.class.getResourceAsStream(...)

+0

感謝您的回覆。我添加了compile.classpath,其中包含了$ {build.classes.dir},它解決了build/classes dir的問題,因爲它已經像你所說的那樣,所以這不是我的問題。 – c12 2012-04-02 21:42:42

+0

唯一可能發生的其他時間(AFAIK)是當你試圖從一個不同於你自己的類的類加載器加載的類加載資源時。嘗試'getClass()。getReasourceAsStream(...)'而不是'prop.getClass()。getResourceAsStream(...)'。讓我知道這是否解決了您的問題,我將更新答案 – Attila 2012-04-03 00:27:53

+0

InputStream is = Testing.class.getClassLoader()。getResourceAsStream(「sample.properties」);工作,感謝您的建議。 – c12 2012-04-03 00:44:54