Java 将对象数组转换为InputStream
我有要测试的程序:Java 将对象数组转换为InputStream,java,unit-testing,Java,Unit Testing,我有要测试的程序: while(true) { //useful code try { id = inputValue(); } catch (InputMatchException e) { System.out.println("blahblah"); } } public int inputValue() throws IOException { InputStream inputStream = ??? Syst
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。有可能吗?循环有条件退出)不用担心。使用
ByteArrayInput/OutputStreams
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write("My string\n".getBytes());
out.write("0".getBytes());
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
然后用扫描仪读取中的
您甚至不需要inputValue()
方法,因为您只需要在设置时调用scanner.nextInt()