2012-04-02 13 views
9

JUnitテストの実行中にクラスパスからsample.propertiesをロードしようとしていますが、クラスパスでファイルを見つけることができません。 Java Mainクラスを作成すると、ファイルをうまく読み込むことができます。私はJUnitを実行するために以下のantタスクを使用しています。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

あなたはcompile.classpath${build.classes.dir}を追加する必要があります。

更新:コメント内の通信に基づいて、classpathが問題ではないことが判明しました。代わりに間違ったクラスローダーが使用されました。

Class.getReasourceAsStream()は、クラスがロードされたクラスローダーに基づいてリソースのパスをルックアップします。その結果、PropertiesクラスはTestingクラスとは異なるクラスローダーによってロードされ、そのクラスローダーのクラスパスに関連してリソースパスが正しくありませんでした。解決策は、Properties.class.getResourceAsStream(...)の代わりにTesting.class.getReasourceAsStream(...)を使用することでした。

+0

応答に感謝します。私は$ {build.classes.dir}を含むcompile.classpathを追加しました。これはビルド/クラスのディレクトリが既に提案したものと同じだからです。残念ながらそれは私の問題ではありません。 – c12

+0

これ以外のとき(AFAIK)は、自分のクラスとは異なるクラスローダーによってロードされたクラスからリソースをロードしようとしているときだけです。 'prop.getClass()。getResourceAsStream(...)'の代わりに 'getClass()。getReasourceAsStream(...)'を試してください。この問題があなたの問題を解決したら私に教えてください。答えは – Attila

+0

です。InputStream is = Testing.class.getClassLoader()。getResourceAsStream( "sample.properties");提案に感謝しました。 – c12

関連する問題