我正在尝试在我的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);**
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
输出:
[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]
Run Code Online (Sandbox Code Playgroud)
Att*_*ila 10
您需要添加${build.classes.dir}到compile.classpath.
更新:基于评论中的沟通,结果证明classpath不是问题.而是使用了错误的类加载器.
Class.getResourceAsStream()根据加载类的类加载器查找资源的路径.事实证明,Properties类是由与类不同的类加载器加载的Testing,并且资源路径与该类加载器的关系不正确classpath.解决方案是使用Testing.class.getResourceAsStream(...)而不是Properties.class.getResourceAsStream(...).
| 归档时间: |
|
| 查看次数: |
27368 次 |
| 最近记录: |