我正在爲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()?
我是不是要讓它變得比它需要更復雜?
也許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
[模擬用戶輸入的JUnit測試]的可能重複(http://stackoverflow.com/questions/6415728/junit-testing-with-simulated-user -input) –