JUnit test for System.out.println()

前端 未结 13 1710
广开言路
广开言路 2020-11-22 03:18

I need to write JUnit tests for an old application that\'s poorly designed and is writing a lot of error messages to standard output. When the getResponse(String reque

13条回答
  •  遇见更好的自我
    2020-11-22 03:45

    Instead of redirecting System.out, I would refactor the class that uses System.out.println() by passing a PrintStream as a collaborator and then using System.out in production and a Test Spy in the test. That is, use Dependency Injection to eliminate the direct use of the standard output stream.

    In Production

    ConsoleWriter writer = new ConsoleWriter(System.out));
    

    In the Test

    ByteArrayOutputStream outSpy = new ByteArrayOutputStream();
    ConsoleWriter writer = new ConsoleWriter(new PrintStream(outSpy));
    writer.printSomething();
    assertThat(outSpy.toString(), is("expected output"));
    

    Discussion

    This way the class under test becomes testable by a simple refactoring, without having the need for indirect redirection of the standard output or obscure interception with a system rule.

提交回复
热议问题