如何使用Junit在Java中测试打印方法 [英] How to test a print method in Java using Junit

查看:872
本文介绍了如何使用Junit在Java中测试打印方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个将输出打印到控制台的方法。我该如何测试?

I have written a method that is printing output to a console. How should I test it?

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

            }
        }
}

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

currently, my test looks like this

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

        }
}

我已经在帖子上阅读了解决方案(感谢@Codebender和@KDM强调这一点),但不太明白。那里的解决方案如何测试print(List items)方法?因此,在这里重新询问。

I have read the solution at this post (thanks @Codebender and @KDM for highlighting this) but don't quite understand it. How does the solution there test the print(List items) method? Hence, asking it afresh here.

推荐答案

既然你已经把你没有得到重复的问题所说的话,我会试试解释一下。

Since you have put you don't get what the duplicate question says, I will try to explain a little.

当你这样做时, System.setOut(OutputStream),无论应用程序写入什么console(使用 System.out.printX())语句,而不是写入你传递的 outputStream

When you do, System.setOut(OutputStream), whatever the application writes to the console (using System.out.printX()) statements, instead get written to the outputStream you pass.

所以,你可以这样做,

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

这篇关于如何使用Junit在Java中测试打印方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆