简体   繁体   中英

Reading System.out Java Test

I have a task to test a console application. I can access one method, but would also like to check that the string formatting is working correctly.

As this method does not return a string, but rather prints to the console, is there a way I can intercept the list printed line?

Does it even make sense to test this sort of thing?

Here is a sample how to catch output to the System.out:

java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();    
System.setOut(new java.io.PrintStream(out));    

System.out.println("Test output");    
System.err.println("Out was: " + out.toString());

You can use System.setOut() to redirect the System.out.println writes to a PrintStream(OutputStream) . Then you can write that OutputStream to a String and test it.

The way for testing this its make a good design with a "output" abstraction instead of print directly to "system.out". For example:

 interface Output {
    void print(String data);
 }

Then you inject this dependency into the class that needs to send information to the output:

class MyProgram {

  private Output out;

  public MyProgram(Output output) {
     this.out = output;
  }

  public doSomething() {
     // do something
     out.print("i do something!);
  }

}

Then you can test easily with a mock (with mockito for example):

public void test_my_program() {

    Output mockOutput = mock(Output.class);
    MyProgram myProgram = new MyProgram(mockOutput);

    myProgram.doSomething();

    verity(mockOutput).print("do something!");
}

I don't verify the code but its more or less correct and i expect enough for you to get the idea. Always its the same, testing its not difficult, the difficult thing its design good testable code, here we are only using abstraction and dependency injection, two basic principles of OO.

The real advantage of this code its that now its not tied to "System.out", you can use this class in a web application for example if you want. For example making and output implementation that talks to the web client via websocket. This is another OO principle, your class is now "Open-Close", you can add functionality (websocket crazy example :P) without modify your actual code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM