2012-11-11 39 views
7

我正在爲java編程競賽寫一些代碼。程序的輸入使用stdin輸出,輸出在stdout上。你如何測試在stdin/stdout上工作的程序?這是我在想什麼:測試從stdin讀取並寫入標準輸出的java程序

由於System.in是InputStream類型和System.out的類型是PrintStream的,我寫我的代碼在FUNC這個原型:

void printAverage(InputStream in, PrintStream out) 

現在,我想喜歡用junit測試這個。我想使用一個字符串僞造System.in,並接收字符串中的輸出。

@Test 
void testPrintAverage() { 

    String input="10 20 30"; 
    String expectedOutput="20"; 

    InputStream in = getInputStreamFromString(input); 
    PrintStream out = getPrintStreamForString(); 

    printAverage(in, out); 

    assertEquals(expectedOutput, out.toString()); 
} 

什麼是 '正確' 的方式來實現getInputStreamFromString()和getPrintStreamForString()?

我是不是要讓它變得比它需要更復雜?

+1

也許http://stackoverflow.com/questions/782178/how-do-i-convert-a-string-to-an-inputstream-in-java和http://stackoverflow.com/questions/216894/ get-an-outputstream-into-a-string可以幫助... – tcovo

+0

[模擬用戶輸入的JUnit測試]的可能重複(http://stackoverflow.com/questions/6415728/junit-testing-with-simulated-user -input) –

回答

6

嘗試以下操作:

String string = "aaa"; 
InputStream stringStream = new java.io.ByteArrayInputStream(string.getBytes()) 

stringStream是從輸入字符串讀甜菜流。

OutputStream outputStream = new java.io.ByteArrayOutputStream(); 
PrintStream printStream = new PrintStream(outputStream); 
// .. writes to printWriter and flush() at the end. 
String result = outputStream.toString() 

printStreamPrintStream將寫入outputStream這反過來將能夠返回一個字符串。

+0

您的意思是PrintStream而不是PrintWriter? – user674669

+0

是的。我在開始時誤解了需要PrintWriter的問題 –

0

編輯:對不起,我誤解了你的問題。

用掃描儀或緩衝讀取器讀取,後者比前者快得多。

Scanner jin = new Scanner(System.in); 

BufferedReader reader = new BufferedReader(System.in); 

用打印作者寫入stdout。您也可以直接打印到Syso,但速度較慢。

System.out.println("Sample"); 
System.out.printf("%.2f",5.123); 

PrintWriter out = new PrintWriter(System.out); 
out.print("Sample"); 
out.close(); 
+0

您無法將'System.in'傳遞到BufferedReader。你需要首先將它包裝在一個'InputStreamReader'中。 – byxor

相關問題