【问题标题】:convert array of objects into InputStream将对象数组转换为 InputStream
【发布时间】:2015-06-18 10:54:57
【问题描述】:

我有我想测试的程序:

while(true) {
//useful code
    try {
        id = inputValue();
    } catch (InputMatchException e) {
        System.out.println("blahblah");
    }
}


public int inputValue() throws IOException {
    InputStream inputStream = ???
    System.setIn(inputStream);
    Scanner scanner = new Scanner(System.in);
    return scanner.nextInt();
}

这里我希望 inputValue 在第一次迭代时返回字符串并导致 catch 块,第二次返回 0。有可能吗?循环有条件退出)不用担心。

【问题讨论】:

    标签: java unit-testing


    【解决方案1】:

    使用ByteArrayInput/OutputStreams

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    
    out.write("My string\n".getBytes());
    out.write("0".getBytes());
    
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    

    然后使用扫描仪从in 读取。

    您甚至不需要inputValue() 方法,因为您只需要在设置时调用scanner.nextInt()

    【讨论】:

      猜你喜欢
      • 2015-08-24
      • 2018-11-20
      • 2017-10-20
      • 2021-05-03
      • 2018-12-04
      • 2021-06-16
      • 1970-01-01
      相关资源
      最近更新 更多