JUnit是否支持测试的属性文件?

问题描述 投票:22回答:5

我有需要在各种不同的临时环境中运行的JUnit测试。每个环境都具有不同的登录凭据或特定于该环境的其他方面。我的计划是将环境变量传递到VM中以指示要使用的环境。然后使用该var从属性文件中读取。

JUnit是否具有读取.properties文件的任何内置功能?

java junit
5个回答
27
投票

java内置了读取.properties文件的功能,JUnit内置了在执行测试套件之前运行安装代码的功能。

java阅读属性:

Properties p = new Properties();
p.load(new FileReader(new File("config.properties")));

junit startup documentation

把这两个放在一起你应该得到你需要的东西。


25
投票

通常首选使用类路径相关文件作为单元测试属性,因此它们可以在不担心文件路径的情况下运行。开发框,构建服务器或任何地方的路径可能不同。这也可以在没有变化的情况下从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”文件放在类路径的根目录下。


1
投票
//
// 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")));

0
投票

你不能只是在你的安装方法中读取属性文件吗?


0
投票

这个答案旨在帮助那些使用Maven的人。

我也更喜欢使用本地类加载器并关闭我的资源。

  1. 创建名为/project/src/test/resources/your.properties的测试属性文件
  2. 如果使用IDE,则可能需要将/ src / test / resources标记为“测试资源根”
  3. 添加一些代码:

// 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);
}
© www.soinside.com 2019 - 2024. All rights reserved.