如何在单元测试中读取配置文件?
我有一个标准的 Maven 项目布局。
一些配置文件存储在src/main/conf
中。
现在我想在 src/test
的单元测试中读取这些文件(例如,从这些文件之一读取属性)。
我怎样才能做到这一点呢?
I have a standard maven project layout.
Some configuration files are stored in src/main/conf
.
Now I would like to read these files in my unit test in src/test
(e.g. read a properties from one of those files).
How can I exactly do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要配置maven以使用这些文件作为测试资源。
只需在
pom.xml
中指定即可。比 maven 会像处理测试资源一样处理你的配置文件。此设置将强制 Maven 在运行单元测试之前将配置文件复制到
target/tests-classes
。然后,您的单元测试将在类路径上包含配置文件,您可以使用 getClass().getResource("/yourConfigFile.conf") 读取它们。
You need to configure maven to use these files as test resources.
Just specify it in
pom.xml
. Than maven will handle your configuration files same as test resources.This settings will force maven to copy configuration files to
target/tests-classes
before running unit tests.Then your unit tests will have configuration files on classpath and you can read them using
getClass().getResource("/yourConfigFile.conf")
.您应该将此类文件放入 src/main/resources 中,这样它们将包含在类路径中并可通过 this.getClass().getResourceFromStream("...") 访问>。
编辑:正如 bbaja42 所说,如果它们仅用于测试,则应放入 src/test/resources 中。
You should put such files in
src/main/resources
, so they will be included on the classpath and accessible throughthis.getClass().getResourceFromStream("...")
.Edit: As bbaja42 says, if they're only used for tests they should go in
src/test/resources
.只是补充 Christoffer 的答案,为了在测试中访问 src/main/conf,您需要将该文件夹添加到您的 maven-surefire-plugin 类路径配置中:
....
然后您就可以从类路径加载文件。假设一个文件为 src/main/conf/test.txt:
this.getClass().getResourceAsStream("/test.txt")
为了在 Eclipse 中运行它,您还需要将该文件夹添加到构建路径中。
您可以在以下位置找到更多信息: http://maven。 apache.org/plugins/maven-surefire-plugin/examples/configuring-classpath.html
Just complementing Christoffer's answer, in order to access src/main/conf within your tests you need to add that folder to your maven-surefire-plugin classpath configuration:
....
Then you'll be able to load files from classpath. Suppose a file as src/main/conf/test.txt:
this.getClass().getResourceAsStream("/test.txt")
In order to run this inside Eclipse you also need to add that folder to your build path as well.
You can find more info at: http://maven.apache.org/plugins/maven-surefire-plugin/examples/configuring-classpath.html