我正在使用Ant 1.8,JUnit 4.8.2。我試圖加載一個屬性文件,並有一些問題。屬性文件位於我的源代碼目錄的根目錄,並將其加載到類路徑中,以及在類路徑中顯式加載屬性文件。下面是我的ant build.xml文件。這是我如何加載屬性...如何使用JUnit/Ant加載屬性文件?
private void loadTestProperties() {
try {
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("db.properties");
prop.load(in);
in.close();
} catch (Exception e) {
fail("Failed to load properties: " + e.getMessage());
} // try
} // loadTestProperties
它總是失敗與空(屬性未加載)。
<project name="leads-testing" default="build" basedir=".">
<property name="tst-dir" location="/Users/davea/Documents/workspace-sts-2.6.0.SR1/infinitiusa_leads_testing/test" />
<property name="db-props-file" location="/Users/davea/Documents/workspace-sts-2.6.0.SR1/infinitiusa_leads_testing/test/db.properties" />
<property name="TALK" value="true" />
<path id="classpath.base">
</path>
<path id="classpath.test">
<pathelement location="lib/junit-4.8.2.jar" />
<pathelement location="lib/selenium-java-client-driver.jar" />
<pathelement location="lib/classes12.jar" />
<pathelement location="${tst-dir}" />
<pathelement location="${db-props-file}" />
<path refid="classpath.base" />
</path>
<target name="compile-test">
<javac srcdir="${tst-dir}"
verbose="${TALK}"
>
<classpath refid="classpath.test"/>
</javac>
</target>
<target name="clean-compile-test">
<delete verbose="${TALK}">
<fileset dir="${tst-dir}" includes="**/*.class" />
</delete>
</target>
<target name="test" depends="compile-test">
<junit>
<classpath refid="classpath.test" />
<formatter type="brief" usefile="false" />
<test name="com.criticalmass.infinitiusa.tests.InfinitiConfigOldG25Base" />
</junit>
</target>
<target name="all" depends="test" />
<target name="clean" depends="clean-compile-test" />
</project>
任何人都知道加載屬性文件的正確方法?謝謝, - 戴夫
這聽起來很對我。我認爲訪問ContextClassLoader的首選方法是通過當前類。所以(我認爲)這會更好:getClass()。getContextClassLoader()。getResourceAsStream(「db.properties」); – 2011-05-06 20:31:37
獲勝者!格維茲,你爲什麼說一種方式比另一種更受歡迎? – Dave 2011-05-06 20:37:43