我正在为Java编程竞赛编写一些代码。程序的输入是使用 stdin 给出的,输出是在 stdout 上。你们如何测试在标准输出/标准输出上运行的程序?这就是我在想的:
由于 System.in 的类型是InputStream,System.out是PrintStream类型,所以我用这个原型在func中编写了我的代码:
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());
}
实现getInputStreamFromString()和getPrintStreamForString()的"正确"方法是什么?
我是否使这比需要的更复杂?
尝试以下操作:
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
而又能够返回字符串。
编辑:对不起,我误读了你的问题。
使用扫描仪或缓冲阅读器读取,后者比前者快得多。
Scanner jin = new Scanner(System.in);
BufferedReader reader = new BufferedReader(System.in);
用印刷作家写到标准输出。您也可以直接打印到 Syso,但这速度较慢。
System.out.println("Sample");
System.out.printf("%.2f",5.123);
PrintWriter out = new PrintWriter(System.out);
out.print("Sample");
out.close();
我正在为Java编程竞赛编写一些代码。程序的输入是使用 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"));