2012-04-02 38 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