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

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

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

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

java阅读属性:

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

junit启动文档

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

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

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

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