如何使用Junit在Java中测试打印方法

Roy*_*Roy 5 java testing junit unit-testing

我编写了一个将输出打印到控制台的方法.我该怎么测试呢?

public class PrinterForConsole implements Printer<Item>{

   public void printResult(List<Item> items) {
        for (Item item: items){
            System.out.println("Name: " + item.getName());
            System.out.println("Number: " + item.getNumber());

            }
        }
}
Run Code Online (Sandbox Code Playgroud)

目前,我的测试看起来像这样

public class TestPrinter{
    @Test
    public void printResultTest() throws Exception {
            (am figuring out what to put here)

        }
}
Run Code Online (Sandbox Code Playgroud)

我已经在这篇文章中阅读了解决方案(感谢@Codebender和@KDM突出显示这一点)但不太明白.那里的解决方案如何测试print(List items)方法?因此,在这里重新询问.

Cod*_*der 13

既然你已经把你没有得到重复的问题,我将尝试解释一下.

当你这样做时System.setOut(OutputStream),无论应用程序写入控制台(使用System.out.printX())语句,都会写入outputStream你的传递.

那么,你可以做点什么,

public void printTest() throws Exception {
      ByteArrayOutputStream outContent = new ByteArrayOutputStream();
      System.setOut(new PrintStream(outContent));

      // After this all System.out.println() statements will come to outContent stream.

     // So, you can normally call,
     print(items); // I will assume items is already initialized properly.

     //Now you have to validate the output. Let's say items had 1 element.
     // With name as FirstElement and number as 1.
     String expectedOutput  = "Name: FirstElement\nNumber: 1" // Notice the \n for new line.

     // Do the actual assertion.
     assertEquals(expectedOutput, outContent.toString());
}
Run Code Online (Sandbox Code Playgroud)


Dak*_*rra 5

测试它的最佳方法是重构它以接受 aPrintStream作为参数,您可以传递另一个PrintStream构造的ByteArrayOutputStream并检查打印到 baos 中的内容。

否则,您可以使用System.setOut将标准输出设置为另一个流。您可以在方法返回后验证写入的内容。

带有注释的简化版本如下:

@Test
public void printTest() throws Exception {
    // Create our test list of items
    ArrayList<Item> items = new ArrayList<Item>();
    items.add(new Item("KDM", 1810));
    items.add(new Item("Roy", 2010));

    // Keep current System.out with us
    PrintStream oldOut = System.out;

    // Create a ByteArrayOutputStream so that we can get the output
    // from the call to print
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // Change System.out to point out to our stream
    System.setOut(new PrintStream(baos));

    print(items);

    // Reset the System.out
    System.setOut(oldOut);

    // Our baos has the content from the print statement
    String output = new String(baos.toByteArray());

    // Add some assertions out output
    assertTrue(output.contains("Name: KDM"));
    assertTrue(output.contains("Name: Roy"));

    System.out.println(output);
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果该print方法抛出异常,System.out则不会重置。最好使用setupteardown方法来设置和重置它。