我被要求在從命令行運行和運行的遺留Java應用程序中引入單元測試。基本上主循環打印出一個菜單,用戶輸入內容並顯示更多數據。JUnit圍繞Sytem.in和System.out進行測試
這個主類說明了應用程序是如何工作的。
public class Main{
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
public static void main(String argv[]) throws IOException{
while (true) {
char input = (char) reader.read();
if(input == 'x'){
return;
}
System.out.println(input);
}
}
}
我想我的測試方法是這個樣子
public void testCaseOne(){
Main.main();
String result = "";
result = sendInput("1");
assertEqual(result, "1");
result = sendInput("x");
assertEqual(result,"");
}
我知道的System.setOut()
和System.setIn()
方法,但我不能想出一個辦法,使System.setIn()
方法工作這種情況下,因爲reader.read()
方法阻止我的線程。
我的測試設計是否錯誤? 有沒有辦法設計sendInput()
方法來完成阻塞reader.read()調用?
如果您希望您的代碼在標準輸入上進行偵聽,同時也將測試代碼寫入標準輸入,那麼順序代碼將不夠用。我相信你需要兩個線程。一個用於Main.main(),另一個用於sendInput(「1」); – mjshaw 2013-02-25 22:05:43
您是否正在測試reader.read()執行正確的操作,還是在傳遞'x'時while循環退出? – 2013-02-25 22:53:31
我甚至會超越Threads,開始使用ProcessBuilder作爲自己的進程測試應用程序。這樣你就不需要擔心重定向任何東西 – radai 2013-02-25 23:02:37