测试从stdin读取并写入stdout的Java程序 [英] Test java programs that read from stdin and write to stdout

查看:476
本文介绍了测试从stdin读取并写入stdout的Java程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java编写一些编程竞赛的代码.程序的输入是使用stdin给出的,输出是在stdout上给出的.你们如何测试可在stdin/stdout上运行的程序?这就是我的想法:

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:

由于System.in的类型为InputStream,而System.out的类型为PrintStream,因此我使用以下原型在函数中编写了代码:

Since System.in is of type InputStream and System.out is of type PrintStream, I wrote my code in a func with this prototype:

void printAverage(InputStream in, PrintStream out)

现在,我想使用junit对此进行测试.我想使用String伪造System.in并以String形式接收输出.

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.

@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()的正确"方法是什么?

What is the 'correct' way to implement getInputStreamFromString() and getPrintStreamForString()?

我使它变得比它需要的复杂吗?

Am I making this more complicated than it needs to be?

推荐答案

尝试以下操作:

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

stringStream是从输入字符串读取字符的流.

stringStream is a stream that will read chars from the input string.

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,而outputStream随后将能够返回字符串.

printStream is a PrintStream that will write to the outputStream which in turn will be able to return a string.

这篇关于测试从stdin读取并写入stdout的Java程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆