我有一个标准的Maven项目结构。
一些配置文件存储在src/main/conf
中。
现在我想在src/test
中读取这些文件(例如从这些文件中读取属性)。
我应该如何做到这一点?
我有一个标准的Maven项目结构。
一些配置文件存储在src/main/conf
中。
现在我想在src/test
中读取这些文件(例如从这些文件中读取属性)。
我应该如何做到这一点?
您需要配置Maven,将这些文件用作测试资源。
只需在pom.xml
中指定即可。然后Maven将处理您的配置文件,就像处理测试资源一样。
<build>
...
<testResources>
<!-- don't forget to specify the default test resources directory -->
<testResource>
<directory>src/test/resources</directory>
</testResource>
<!-- add the config directory -->
<testResource>
<directory>src/main/conf</directory>
</testResource>
</testResources>
...
</build>
这个设置会强制Maven在运行单元测试之前将配置文件复制到target/tests-classes
目录下。
然后你的单元测试就可以使用类路径上的配置文件,并且可以使用getClass().getResource("/yourConfigFile.conf")
来读取它们。
src/main/resources
或 src/test/resources
中会简单得多。 - Christoffer Hammarström补充Christoffer的答案,为了在测试中访问src/main/conf,您需要将该文件夹添加到maven-surefire-plugin类路径配置中:
<build>
<plugins>
.....
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalClasspathElements>
<additionalClasspathElement>src/main/conf</additionalClasspathElement>
</additionalClasspathElements>
</configuration>
</plugin>
您可以从类路径中加载文件。假设有一个文件位于 src/main/conf/test.txt:
this.getClass().getResourceAsStream("/test.txt")
为了在 Eclipse 中运行此代码,您还需要将该文件夹添加到构建路径中。
您可以在以下链接中找到更多信息:http://maven.apache.org/plugins/maven-surefire-plugin/examples/configuring-classpath.html
src/main/resources
或 src/test/resources
中会更加简单。 - Christoffer Hammarströmthis.getClass().getResourceAsStream("/test.txt")
中似乎需要加上 /
。如果写成 this.getClass().getResourceAsStream("test.txt")
,就无法正常工作。这一点起初并不是很明显。 - Patricksrc/main/resources
目录下,这样它们就会被包含在类路径中,并通过 this.getClass().getResourceFromStream("...")
访问。src/test/resources
目录下。src/test/resources
目录下吗? - bbaja42src/main/resources
,避免资源的(可能冲突的)副本。 - Keith Laynethis.getClass().getResourceFromStream("...")
会在类路径上查找,测试中包含src/main/resources
和src/test/resources
。没有特殊的设置。 - Christoffer Hammarström