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

时间:2012-11-11 07:08:16

标签: java junit mocking

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

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

void printAverage(InputStream in, PrintStream out)

现在,我想用junit测试一下。我想使用String伪造System.in并以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()的'正确'方法是什么?

我是否比这更复杂?

3 个答案:

答案 0 :(得分:6)

尝试以下方法:

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

stringStream是一个将从输入字符串中读取chard的流。

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,而{{1}}又可以返回一个字符串。

答案 1 :(得分:0)

编辑:对不起,我误解了你的问题。

使用scanner或bufferedreader读取,后者比前者快得多。

Scanner jin = new Scanner(System.in);

BufferedReader reader = new BufferedReader(System.in);

使用print writer写入stdout。您也可以直接打印到Syso,但速度较慢。

System.out.println("Sample");
System.out.printf("%.2f",5.123);

PrintWriter out = new PrintWriter(System.out);
out.print("Sample");
out.close();

答案 2 :(得分:0)

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

将字符发送到System.in的另一种方法是使用PipedInputStreamPipedOutputStream。也许像下面这样:

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"));
相关问题