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