[英]Test java programs that read from stdin and write to stdout
我正在為 Java 編程競賽編寫一些代碼。 程序的輸入使用 stdin 給出,輸出在 stdout 上。 你們如何測試在標准輸入/標准輸出上工作的程序? 這就是我的想法:
由於 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() 的“正確”方法是什么?
我是否使這比需要的更復雜?
請嘗試以下操作:
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()
printStream
是一個PrintStream
,它將寫入outputStream
,后者又將能夠返回一個字符串。
編輯:對不起,我誤讀了你的問題。
用scanner或bufferedreader讀取,后者比前者快很多。
Scanner jin = new Scanner(System.in);
BufferedReader reader = new BufferedReader(System.in);
使用打印寫入器寫入標准輸出。 您也可以直接打印到 Syso,但速度較慢。
System.out.println("Sample");
System.out.printf("%.2f",5.123);
PrintWriter out = new PrintWriter(System.out);
out.print("Sample");
out.close();
我正在為 Java 編程競賽編寫一些代碼。 程序的輸入使用 stdin 給出,輸出在 stdout 上。 你們如何測試在標准輸入/標准輸出上工作的程序?
另一種將字符發送到System.in
是使用PipedInputStream
和PipedOutputStream
。 也許類似於以下內容:
PipedInputStream pipeIn = new PipedInputStream(1024);
System.setIn(pipeIn);
PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);
// then I can write to the pipe
pipeOut.write(new byte[] { ... });
// if I need a writer I do:
Writer writer = OutputStreamWriter(pipeOut);
writer.write("some string");
// call code that reads from System.in
processInput();
另一方面,正如@Mihai Toader 所提到的,如果我需要測試System.out
那么我會執行以下操作:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
// call code that prints to System.out
printSomeOutput();
// now interrogate the byte[] inside of baos
byte[] outputBytes = baos.toByteArray();
// if I need it as a string I do
String outputStr = baos.toString();
Assert.assertTrue(outputStr.contains("some important output"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.