在JUnit @BeforeClass中加载属性文件

时间:2012-04-02 20:34:21

标签: java ant junit

我正在尝试在JUnit测试执行期间从我的类路径加载sample.properties,但它无法在类路径中找到该文件。如果我编写Java Main类,我可以正常加载文件。我正在使用下面的ant任务来执行我的JUnit。

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]

2 个答案:

答案 0 :(得分:9)

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

更新:根据评论中的沟通,结果发现classpath不是问题。而是使用了错误的类加载器。

Class.getResourceAsStream()根据加载类的类加载器查找资源的路径。事实证明,Properties类是由与Testing类不同的类加载器加载的,并且资源路径与该类加载器classpath的关系不正确。解决方案是使用Testing.class.getResourceAsStream(...)代替Properties.class.getResourceAsStream(...)

答案 1 :(得分:0)

这有效:

YourTestClass.class.getClassLoader().getResourceAsStream

无效

YourTestClass.class.getResourceAsStream