【问题标题】:How do I load a properties file with JUnit / Ant?如何使用 JUnit / Ant 加载属性文件?
【发布时间】:2011-05-06 19:41:27
【问题描述】:

我正在使用 Ant 1.8、JUnit 4.8.2。我正在尝试加载属性文件并遇到一些问题。属性文件位于我的源目录的根目录中,我将其加载到类路径中,并在类路径中显式加载属性文件。下面是我的 ant build.xml 文件。这是我尝试加载属性的方式……

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

它总是以 null 失败(未加载属性)。

<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>

有人知道加载属性文件的正确方法吗?谢谢, - 戴夫

【问题讨论】:

    标签: java ant junit


    【解决方案1】:

    尝试从getClass().getResourceAsStream() 加载资源将导致根据类的包名查找db.properties,即在类似com/criticalmass/infinitiusa/... 的目录(在类路径中)中。

    相反,要从类路径的根目录加载,请尝试类似

    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
    

    【讨论】:

    • 这听起来不错。我认为访问 ContextClassLoader 的首选方式是通过当前类。所以(我认为)这会更好:getClass().getContextClassLoader().getResourceAsStream("db.properties");
    • 赢家! Gweebz,你为什么说一种方式优于另一种方式?
    【解决方案2】:
    InputStream in = getClass().getResourceAsStream("db.properties");
    

    改用"/db.properties"。见Class.getResourceAsStream()

    对于 Ant,文件路径是相对于工作目录进行解析的。因此,如果从项目根目录运行,文件将位于src/${db-props-file}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-19
      • 2011-05-09
      • 2012-07-06
      • 2012-04-16
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多