【发布时间】:2009-10-12 23:53:58
【问题描述】:
我有需要在各种不同的暂存环境中运行的 JUnit 测试。每个环境都有不同的登录凭据或特定于该环境的其他方面。我的计划是将环境变量传递给 VM 以指示要使用的环境。然后使用该 var 从属性文件中读取。
JUnit 是否具有读取 .properties 文件的内置功能?
【问题讨论】:
我有需要在各种不同的暂存环境中运行的 JUnit 测试。每个环境都有不同的登录凭据或特定于该环境的其他方面。我的计划是将环境变量传递给 VM 以指示要使用的环境。然后使用该 var 从属性文件中读取。
JUnit 是否具有读取 .properties 文件的内置功能?
【问题讨论】:
对于单元测试属性,通常首选使用类路径相关文件,这样它们就可以运行而不必担心文件路径。在您的开发盒、构建服务器或其他任何地方,路径可能会有所不同。这也适用于 ant、maven、eclipse,无需更改。
private Properties props = new Properties();
InputStream is = ClassLoader.getSystemResourceAsStream("unittest.properties");
try {
props.load(is);
}
catch (IOException e) {
// Handle exception here
}
将“unittest.properties”文件放在类路径的根目录下。
【讨论】:
src/test/resources,这是正确的解决方案
java 内置了读取 .properties 文件的功能,而 JUnit 内置了在执行测试套件之前运行设置代码的功能。
java读取属性:
Properties p = new Properties();
p.load(new FileReader(new File("config.properties")));
把这两个放在一起,你应该有你需要的。
【讨论】:
//
// Load properties to control unit test behaviour.
// Add code in setUp() method or any @Before method (JUnit4).
//
// Corrected previous example: - Properties.load() takes an InputStream type.
//
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
Properties p = new Properties();
p.load(new FileInputStream( new File("unittest.properties")));
// loading properties in XML format
Properties pXML = new Properties();
pXML.loadFromXML(new FileInputStream( new File("unittest.xml")));
【讨论】:
这个答案旨在帮助那些使用 Maven 的人。
我也更喜欢使用本地类加载器并关闭我的资源。
创建名为 /project/src/test/resources/your.properties 的测试属性文件
如果您使用 IDE,您可能需要将 /src/test/resources 标记为“测试资源根目录”
添加一些代码:
// inside a YourTestClass test method
try (InputStream is = loadFile("your.properties")) {
p.load(new InputStreamReader(is));
}
// a helper method; you can put this in a utility class if you use it often
// utility to expose file resource
private static InputStream loadFile(String path) {
return YourTestClass.class.getClassLoader().getResourceAsStream(path);
}
【讨论】:
如果目标是将.properties 文件加载到系统属性中,那么系统存根 (https://github.com/webcompere/system-stubs) 可以提供帮助:
SystemProperties 对象可以用作 JUnit 4 规则以在测试方法中应用它,也可以用作 JUnit 5 插件的一部分,它允许从属性文件设置属性:
SystemProperties props = new SystemProperties()
.set(fromFile("src/test/resources/test.properties"));
然后需要激活SystemProperties 对象。这可以通过在 JUnit 5 中使用 @SystemStub 标记它,或者通过在 JUnit4 中使用其 SystemPropertiesRule 子类,或者通过在 SystemProperties execute 方法中执行测试代码来实现。
【讨论】: