将属性加载到InputStream中

时间:2018-08-21 18:15:24

标签: java unit-testing

我有一个使用InputStream作为参数的方法。该方法从InputStream中提取Properties,然后返回“ version”属性。此属性保存应用程序的版本。

public String getVersion(InputStream inputStream) throws IOException {
    Properties properties = new Properties();
    properties.load(inputStream);
    String version = properties.getProperty("version");
    return version;
}

出于测试目的,我想创建一个Properties对象,设置一些属性,然后将这些属性加载到InputStream中。最后,将InputStream传递给被测方法。

@Test
public void testGetAppVersion() {
    InputStream inputStream = null;
    Properties prop = new Properties();
    prop.setProperty("version", "1.0.0.test");

    // Load properties into InputStream
}

我将如何处理?

1 个答案:

答案 0 :(得分:6)

您可以使用store方法将属性写入流。

这是一个使用字节数组流的示例:

Properties prop = new Properties();
prop.put("version", "1.0.0.test");

ByteArrayOutputStream os = new ByteArrayOutputStream();
props.store(os, "comments");

InputStream s = new ByteArrayInputStream(os.toByteArray());

String version = getVersion(s);

但是我相信以下方法更简单(来自字符串文件内容的输入流):

InputStream is = 
    new ByteArrayInputStream("version=1.0.0.test\n".getBytes());