我有一個類,其中用戶在終端窗口上進行交互,並在某些選項中鍵入,並根據這些選項進行切換並使用某些方法;我需要使用掃描儀來檢測用戶輸入。如何模擬掃描儀的用戶輸入?
我試了幾天做一個測試類來模擬用戶輸入,但我找不到合適的方法來做,因爲我無法模擬掃描儀的System.in,也沒有找到任何具體的信息,我已經看到了一些緩衝,但我不能使用它。
這是一次嘗試,這將導致掃描程序發生nullPointerException異常 - 因爲沒有檢測到輸入。我還嘗試睡眠,然後設置輸入。
一個模擬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上,因爲它是遞歸方法,直到給出某個選項來終止程序。
*「這是一次嘗試,導致掃描程序出現nullPointerException - 因爲沒有檢測到輸入」* Stacktrace? – Tom
*「它在TEMP-2停止,因爲它是遞歸方法,直到給出某個選項來終止程序。」*那麼,爲什麼不提供該特定選項作爲輸入而不是使用空字符串? – Tom
爲什麼不使用'new Scanner(new File(「simulatedUserInput.txt」))'而不是試圖模擬'System.in'? –