How Java unit tests assert (check) console output

Source: Internet
Author: User

It is a long-standing problem for me to assert the console output of a function in JUnit unit tests. Although a function with console output has side effects and cannot be called a pure function, in today's functional programming, pure functions are best tested, called data in, and data out. However, there is always such a requirement, such as the Appender of a log framework that is implemented by itself, and the need to verify its output to the console.

My previous approach in the project was to direct the standard output to aByteArrayOutputStreamIn the end, and then turn this into a string to assert its contents, and finally restore the standard output toSystem.out, the code is as follows:

Bytearrayoutputstream output = new Bytearrayoutputstream ();
System.setout (new PrintStream (output));

System.out.print ("Hello");

Assertthat (Output.tostring (), is ("Hello");
System.setout (System.out);

This also can complete the task, the essence is right, but slightly more complicated. Read todaySpring in ActionA book and found it usedStandardOutputStreamLogThis JUnit's@Rule, from System Rules. In factStandardOutputStreamLogClass is deprecated and replaced with systemoutrule, so the applicationSystemOutRuleThe test method to assert the console output is to read the full text >>


How Java unit tests assert (check) console output

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.