简体   繁体   English

阅读System.out Java测试

[英]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: 以下是如何捕获输出到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) . 您可以使用System.setOut()System.out.println写入重定向到PrintStream(OutputStream) Then you can write that OutputStream to a String and test it. 然后,您可以将OutputStream写入String并对其进行测试。

The way for testing this its make a good design with a "output" abstraction instead of print directly to "system.out". 测试它的方法是使用“输出”抽象而不是直接打印到“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): 然后你可以使用mock轻松测试(例如mockito):

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. 总是它一样,测试它并不难,其设计好的可测试代码很难,这里我们只使用抽象和依赖注入,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. 这段代码的真正优势在于它现在与“System.out”无关,您可以在Web应用程序中使用此类,例如,如果您需要。 For example making and output implementation that talks to the web client via websocket. 例如,通过websocket与Web客户端通信的制作和输出实现。 This is another OO principle, your class is now "Open-Close", you can add functionality (websocket crazy example :P) without modify your actual code. 这是另一个OO原则,你的类现在是“Open-Close”,你可以添加功能(websocket疯狂的例子:P)而无需修改你的实际代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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