JUnit 是否支持测试属性文件?
我有需要在各种不同的暂存环境中运行的 JUnit 测试。每个环境都有不同的登录凭据或特定于该环境的其他方面。我的计划是将环境变量传递到虚拟机中以指示要使用的环境。然后使用该 var 从属性文件中读取。
JUnit 是否具有读取 .properties 文件的内置功能?
I have JUnit tests that need to run in various different staging environments. Each of the environments have different login credentials or other aspects that are specific to that environment. My plan is to pass an environment variable into the VM to indicate which environment to use. Then use that var to read from a properties file.
Does JUnit have any build in capabilities to read a .properties file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
通常首选使用类路径相对文件作为单元测试属性,这样它们就可以运行而不必担心文件路径。您的开发盒、构建服务器或任何地方的路径可能不同。这也适用于 ant、maven、eclipse,无需更改。
将“unittest.properties”文件放在类路径的根目录下。
It is usually preferred to use class path relative files for unit test properties, so they can run without worrying about file paths. The path may be different on your dev box, or the build server, or where ever. This will also work from ant, maven, eclipse without changes.
putting the "unittest.properties" file at the root of the classpath.
java 具有读取 .properties 文件的内置功能,而 JUnit 具有在执行测试套件之前运行设置代码的内置功能。
java阅读属性:
junit启动文档
将这两个放在一起,你应该有你需要什么。
java has built in capabilities to read a .properties file and JUnit has built in capabilities to run setup code before executing a test suite.
java reading properties:
junit startup documentation
put those 2 together and you should have what you need.
这个答案旨在帮助那些使用 Maven 的人。
我也更喜欢使用本地类加载器并关闭我的资源。
创建测试属性文件,名为 /project/src/test/resources/your.properties
如果使用 IDE,您可能需要将 /src/test/resources 标记为“测试资源根”
添加一些代码:
This answer is intended to help those who use Maven.
I also prefer to use the local classloader and close my resources.
Create your test properties file, called /project/src/test/resources/your.properties
If you use an IDE, you may need to mark /src/test/resources as a "Test Resources root"
add some code:
如果目标是将
.properties
文件加载到系统属性中,则系统存根 (https://github.com/webcompere/system-stubs)可以提供帮助:SystemProperties
对象,它可以用作 JUnit 4 规则以将其应用到测试方法中,或作为 JUnit 5 插件的一部分,允许从属性文件设置属性:然后需要激活
SystemProperties
对象。这是通过在 JUnit 5 中用@SystemStub
标记它,或者在 JUnit4 中使用它的SystemPropertiesRule
子类,或者通过在SystemProperties< 中执行测试代码来实现的。 /code>
执行
方法。If the aim is to load a
.properties
file into System Properties, then System Stubs (https://github.com/webcompere/system-stubs) can help:The
SystemProperties
object, which can be used either as a JUnit 4 rule to apply it within a test method, or as part of the JUnit 5 plugin, allows setting properties from a properties file:The
SystemProperties
object then needs to be made active. This is achieved either by marking it with@SystemStub
in JUnit 5, or by using itsSystemPropertiesRule
subclass in JUnit4, or by executing the test code inside theSystemProperties
execute
method.