Java 将字符串传递到输入流

Java 将字符串传递到输入流,java,inputstream,Java,Inputstream,有人写了一个我想测试的类。它看起来像: public class foo <E>{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); do_stuff(scan.nextInt()); } } 公共类foo{ 公共静态void main(字符串[]args){ 扫描仪扫描=新扫描仪(System.in); dou_s

有人写了一个我想测试的类。它看起来像:

public class foo <E>{  
     public static void main(String[] args){
         Scanner scan = new Scanner(System.in);
         do_stuff(scan.nextInt());
     }
}
公共类foo{
公共静态void main(字符串[]args){
扫描仪扫描=新扫描仪(System.in);
dou_stuff(scan.nextInt());
}
}
我有另一个类,它尝试测试上述函数的主要方法,如下所示:

public class Test{
   public static void main(String[] args){
        System.in.read("5".getBytes());
        foo.<Integer>main(new String[]{});
   }
}
公共类测试{
公共静态void main(字符串[]args){
System.in.read(“5.getBytes());
main(新字符串[]{});
}
}
基本上,我正在尝试使用测试类将输入馈送到流中,该流将很快被foo中的扫描器读取。我根本无法更改foo,因为它是其他人的代码


为什么这样不行?正确的方法是什么?

您的
系统.in.read(“5.getBytes())
所做的是将字节数组传递给
read
方法,该方法尝试用用户输入填充它。它完全忽略您放入该字节数组中的数据

您必须调用
System.setIn()
来更改连接到
System.in的流。

System.setIn(new ByteArrayInputStream("5".getBytes()));
foo.<Integer>main(new String[]{});
System.setIn(新的ByteArrayInputStream(“5.getBytes()));
main(新字符串[]{});

你能直接调用
doStuff
方法吗?它是您应该测试的,因为没有必要测试languaje定义的东西。(就像我要测试
+
操作符是否工作一样;这已经被languaje开发人员测试过了)另外,您应该查看或任何其他测试框架。