测试从标准输入读取和输出到标准输出的方法

时间:2015-03-24 22:58:55

标签: java unit-testing testing junit

我有一种方法,它从标准输入读取行并将行写入标准输出。

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

1 个答案:

答案 0 :(得分:16)

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

你应该有一个方法接受它所读取的InputStream和它所写的PrintStream作为参数。 (这是一个应用程序,在方法层面,被称为Dependency Injection (Wikipedia)的原则,通常在班级使用。)

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

但是当你想测试它时,你可以传递一个InputStreamPrintStream来为测试目的而创建它。

所以,你可以沿着这些方向使用:

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 );
}
相关问题