12

我正在为 Java 编程竞赛编写一些代码。程序的输入使用标准输入给出,输出在标准输出上。你们是如何测试在标准输入/标准输出上工作的程序的?这就是我的想法:

由于 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() 的“正确”方法是什么?

我是否使这比需要的更复杂?

4

3 回答 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后者又将能够返回一个字符串。

于 2012-11-11T07:21:02.067 回答
0

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

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

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();
于 2012-11-11T07:13:54.460 回答
0

我正在为 Java 编程竞赛编写一些代码。程序的输入使用标准输入给出,输出在标准输出上。你们是如何测试在标准输入/标准输出上工作的程序的?

另一种发送字符的方法System.in是使用PipedInputStreamand 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"));
于 2020-06-05T19:47:04.367 回答