Writing data to System.in

我只是一个虾纸丫 提交于 2019-11-27 15:05:20

问题


In our application, we expect user input within a Thread as follows :

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

I want to pass that part in my unit test so that I can resume the thread to execute the rest of the code. How can I write something into System.in from junit?


回答1:


What you want to do is use the method setIn() from System. This will let you pass data into System.in from junit.




回答2:


Replace it for the duration of your test:

String data = "the text you want to send";
InputStream testInput = new ByteArrayInputStream( data.getBytes("UTF-8") );
InputStream old = System.in;
try {
    System.setIn( testInput );

    ...
} finally {
    System.setIn( old );
}



回答3:


Instead of the suggestions above (edit: I noticed that Bart left this idea in a comment as well), I would suggest making your class more unit testable by making the class accept the input source as a constructor parameter or similar (inject the dependency). A class shouldn't be so coupled to System.in anyway.

If your class is constructed from a Reader, you can just do this:

class SomeUnit {
   private final BufferedReader br;
   public SomeUnit(Reader r) {
       br = new BufferedReader(r);
   }
   //...
}

//in your real code:
SomeUnit unit = new SomeUnit(new InputStreamReader(System.in));

//in your JUnit test (e.g.):
SomeUnit unit = new SomeUnit(new StringReader("here's the input\nline 2"));



回答4:


My solution currently (in 2018) is:

 final byte[] passCode = "12343434".getBytes();
 final ByteArrayInputStream inStream = new ByteArrayInputStream(passCode);
        System.setIn(inStream);


来源:https://stackoverflow.com/questions/3814055/writing-data-to-system-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!