Tôi đang cố gắng tải mẫu.properties từ đường dẫn lớp của mình trong quá trình thực hiện kiểm tra JUnit và không thể tìm thấy tệp trong đường dẫn lớp. Nếu tôi viết một lớp Java chính tôi có thể tải tập tin tốt. Tôi đang sử dụng nhiệm vụ kiến dưới đây để thực hiện JUnit của tôi.Tải tệp thuộc tính vào 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>
Output:
[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]
cảm ơn phản hồi. Tôi đã thêm tệp compile.classpath bao gồm $ {build.classes.dir} để giải quyết việc xây dựng/lớp thư mục ở trên vì nó đã giống như những gì bạn đề xuất, vì vậy đó không phải là vấn đề của tôi. – c12
Chỉ một lần khác điều này có thể xảy ra (AFAIK) là khi bạn đang cố tải tài nguyên từ một lớp được nạp bởi một trình nạp lớp khác với lớp của riêng bạn. Hãy thử 'getClass(). GetReasourceAsStream (...)' thay vì 'prop.getClass(). GetResourceAsStream (...)'. Hãy cho tôi biết nếu điều này khắc phục được sự cố của bạn và tôi sẽ cập nhật câu trả lời – Attila
InputStream là = Testing.class.getClassLoader(). GetResourceAsStream ("sample.properties"); đã làm việc, cảm ơn đề nghị. – c12