【问题标题】:Test java programs that read from stdin and write to stdout测试从标准输入读取并写入标准输出的 java 程序
【发布时间】:2012-10-31 00:35:46
【问题描述】:

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

我是否让这变得比它需要的更复杂?

【问题讨论】:

标签: java junit mocking


【解决方案1】:

已编辑:抱歉,我误读了您的问题。

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

【讨论】:

  • 您不能将 System.in 传递给 BufferedReader。您需要先将其包装在 InputStreamReader 中。
【解决方案2】:

尝试以下方法:

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,而outputStream 又将能够返回一个字符串。

【讨论】:

  • 您的意思是 PrintStream 而不是 PrintWriter?
  • 是的。我一开始就把这个问题误读为需要一个 PrintWriter
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 2015-01-31
    • 2012-04-25
    • 2012-09-25
    • 2017-08-20
    • 1970-01-01
    相关资源
    最近更新 更多