是否JUnit支持性文件进行测试?(Does JUnit support properties fi

2019-07-22 18:00发布

我需要在各种不同的分期的环境中运行JUnit测试。 每个环境都有不同的登录凭证或其他方面所特有的那种环境。 我的计划是一个环境变量传递到虚拟机,以指示要使用的环境。 然后使用VAR从属性文件中读取。

JUnit的是否有能力建造任何读取.properties文件?

Answer 1:

Java有内置的功能来读取属性文件和JUnit已建成功能执行测试套件之前,运行安装程序代码。

Java的阅读性能:

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

JUnit的启动文件

把那些2在一起,你应该有你需要的东西。



Answer 2:

它通常是优选使用类路径相对文件的单元测试性能,因此它们可以无需担心文件路径运行。 路径可能会在你的开发中,或构建服务器,或者其它任何不同。 这也会从蚂蚁,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”文件在classpath的根目录。



Answer 3:

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


Answer 4:

你就不能看在你的设置方法的属性文件?



Answer 5:

这个答案是为了帮助那些谁使用Maven。

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

  1. 创建测试属性文件,名为/project/src/test/resources/your.properties

  2. 如果你使用的是IDE,你可能需要标记/ src目录/测试/资源作为“测试资源根”

  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);
}


文章来源: Does JUnit support properties files for tests?
标签: java junit