java stdout,测试从stdin读取并写入stdout的Java程序

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:

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)

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());

}

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

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

解决方案

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值