【问题标题】:Testing a method that reads from standard input and outputs to standard output测试从标准输入和输出读取到标准输出的方法
【发布时间】:2015-03-24 22:58:54
【问题描述】:

我有一个从标准输入读取行并将行写入标准输出的方法。

在 JUnit 测试中,如何向方法发送输入,如何捕获其输出以便对其进行断言?

【问题讨论】:

标签: java unit-testing testing junit


【解决方案1】:

你不应该有一个从标准输入读取并写入标准输出的方法。

您应该有一个方法,该方法接受它从中读取的InputStream 和它写入的PrintStream 作为参数。 (这是在方法级别的应用程序,称为Dependency Injection (Wikipedia),通常用于类级别。)

然后,在正常情况下,您调用该方法并将System.inSystem.out 作为参数传递给它。

但是当你想测试它时,你可以传递一个InputStream 和一个你为测试目的创建的PrintStream

因此,您可以使用以下方法:

void testMyAwesomeMethod( String testInput, String expectedOutput )
{
    byte[] bytes = testInput.getBytes( StandardCharsets.UTF_8 );
    InputStream inputStream = new ByteArrayInputStream( bytes );
    StringWriter stringWriter = new StringWriter();
    try( PrintWriter printWriter = new PrintWriter( stringWriter ) )
    {
        myAwesomeMethod( inputStream, printWriter );
    }
    String result = stringWriter.toString();
    assert result.equals( expectedOutput );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-31
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 2014-08-05
    • 1970-01-01
    • 2012-04-25
    相关资源
    最近更新 更多