在JUnit @BeforeClass中加载属性文件

我正在尝试在我的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的:

                   

输出:

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

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

更新 :基于评论中的通信,事实certificateclasspath不是问题。 而是使用了错误的类加载器。

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