我有一个类,用户在终端窗口上进行交互并输入某些选项,根据这些选项进行切换并使用某些方法;我需要使用扫描仪来检测用户输入。
我尝试了几天来创建一个测试类来模拟用户输入,但我找不到合适的方法,因为我无法为扫描仪模拟 System.in,也没有找到任何具体信息,我看到了一些关于缓冲,但我不能使用它。
这是一个尝试,它导致扫描仪出现 nullPointerException - 因为没有检测到输入。我还尝试休眠然后设置输入。
非常感谢为 Scanner 模拟 System.in 的示例。
public void test1addItem()
{
InputStream input = new ByteArrayInputStream("".getBytes());
String data1="1"; //Add an item option
String data2="bread"; //The item to add
input = new ByteArrayInputStream(data1.getBytes());
//System.out.println("DATA1="+input);
System.out.println("TEMP - 1");
System.setIn(input);
System.out.println("TEMP - 2");
tsl.start(); //reference to the class which I am testing
System.out.println("TEMP - 3");
try {
Thread.sleep(2000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("TEMP - 4");
input = new ByteArrayInputStream(data2.getBytes());
System.out.println("TEMP - 5");
System.setIn(input);
System.out.println("TEMP - 6");
}
它在 TEMP - 2 处停止,因为它是一种递归方法,直到给出某个选项来终止程序。