测试从标准输入读取并写入标准输出的 Java 程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13329282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Test java programs that read from stdin and write to stdout
提问by user674669
I am writing some code for a programming contest in java. The input to the program is given using stdin and output is on stdout. How are you folks testing programs that work on stdin/stdout? This is what I am thinking:
我正在为 Java 编程竞赛编写一些代码。程序的输入是使用 stdin 给出的,输出是在 stdout 上的。你们如何测试在标准输入/标准输出上工作的程序?这就是我的想法:
Since System.in is of type InputStream and System.out is of type PrintStream, I wrote my code in a func with this prototype:
由于 System.in 是 InputStream 类型,System.out 是 PrintStream 类型,我用这个原型在 func 中编写了我的代码:
void printAverage(InputStream in, PrintStream out)
Now, I would like to test this using junit. I would like to fake the System.in using a String and receive the output in a String.
现在,我想使用 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());
}
What is the 'correct' way to implement getInputStreamFromString() and getPrintStreamForString()?
实现 getInputStreamFromString() 和 getPrintStreamForString() 的“正确”方法是什么?
Am I making this more complicated than it needs to be?
我是否使这比需要的更复杂?
采纳答案by Mihai Toader
Try the following:
请尝试以下操作:
String string = "aaa";
InputStream stringStream = new java.io.ByteArrayInputStream(string.getBytes())
stringStream
is a stream that will read chars from the input string.
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
is a PrintStream
that will write to the outputStream
which in turn will be able to return a string.
printStream
是PrintStream
将写入 的outputStream
,而后者将能够返回一个字符串。
回答by Willem
EDITED: Sorry I misread your question.
编辑:对不起,我误读了你的问题。
Read with scanner or bufferedreader, The latter is much faster than the former.
用scanner或者bufferedreader读取,后者比前者快很多。
Scanner jin = new Scanner(System.in);
BufferedReader reader = new BufferedReader(System.in);
Write to stdout with print writer. You can also print directly to Syso but this is slower.
使用打印写入器写入标准输出。您也可以直接打印到 Syso,但速度较慢。
System.out.println("Sample");
System.out.printf("%.2f",5.123);
PrintWriter out = new PrintWriter(System.out);
out.print("Sample");
out.close();