[英]Loading property file for maven-surefire-plugin
我有一个testng类,该类测试一个类,该类依次从classpath加载属性。当我运行maven install时,我收到一个错误提示文件,找不到文件。尽管我在src/test/resources
有它,但它找不到属性文件src/test/resources
。 如何解决这个问题?
Java代码具有一个试图加载属性文件的构造函数。 Properties props = JobUtils .loadProperties("x.properties");
我的Maven配置:
<plugin>
<groupId>org.apache.maven.plugins
<artifactId>maven-surefire-plugin
<version>2.5
<configuration>
<skipTests>false</skipTests>
</configuration>
</plugin>
与:
<build>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>false</filtering>
</testResource>
</testResources>
</build>
我在src/test/resource
也有这个x.properties
运行TestSuite的堆栈跟踪为:
java.io.FileNotFoundException: x.properties (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(FileInputStream.java:106)
at java.io.FileInputStream.(FileInputStream.java:66)
还要注意我尝试实例化此Java代码并对其进行测试的测试类。
在执行Maven process-test-resources
阶段之后,实际上x.properties
src/test/resources
目录中的x.properties
文件复制到target/test-classes
目录中。 因此,如果希望您的应用程序能够找到它,则应使用以下文件路径:
Properties props = JobUtils .loadProperties("target/test-classes/x.properties");
但是我不认为这正是您要寻找的。 我建议使用如下代码直接从CLASSPATH中读取属性文件(不直接使用文件系统):
InputStream is = getClass().getResourceAsStream("/x.properties");
Properties p = new Properties();
try {
p.load(is);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用这种方法,您甚至可以从分发给客户的JAR文件中,或者从以某种启动脚本添加到CLASSPATH中的配置文件中加载属性文件。
我遇到了找不到文件的相同问题。 但是,当我在命令行上运行mvn test时,我意识到maven可以使用它。 只是我的Eclipse IDE告诉我找不到它。 当我在IDE目录src / test / resources中将其更改为“源目录”时,我的IDE也很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.