测试从标准输入读取并写入标准输出的Java程序。

13

我正在用Java为编程竞赛编写一些代码。程序的输入是使用stdin给出,输出是在stdout上。您们是如何测试适用于stdin / stdout 的程序的呢?这是我的想法:

由于System.in是InputStream类型,而System.out是PrintStream类型,因此我编写了一个具有以下原型的函数:

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

'correct'方法实现getInputStreamFromString()和getPrintStreamForString()是什么?

我是否把它搞复杂了?


1
也许这些链接可以帮助解决问题:https://dev59.com/tHRA5IYBdhLWcg3w6SXZ和https://dev59.com/BHVC5IYBdhLWcg3wrDNd。 - tcovo
可能是使用模拟用户输入进行JUnit测试的重复问题。 - Jeff Bowman
3个回答

7
尝试以下操作:
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,后者又可以返回一个字符串。


你是不是想用PrintStream而不是PrintWriter? - user674669
是的,我一开始误读了问题,以为需要一个PrintWriter。 - Mihai Toader

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

你不能直接将 System.in 传递给 BufferedReader。你需要先将其包装在一个 InputStreamReader 中。 - byxor

0
我正在使用Java为编程竞赛编写一些代码。程序的输入是通过stdin给出的,输出在stdout上。你们是如何测试使用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"));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接