Writing data to System.in

前端 未结 4 1006
感情败类
感情败类 2020-12-14 21:42

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

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


        
相关标签:
4条回答
  • 2020-12-14 22:21

    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"));
    
    0 讨论(0)
  • 2020-12-14 22:26

    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 );
    }
    
    0 讨论(0)
  • 2020-12-14 22:29

    My solution currently (in 2018) is:

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

    [Update in 2019] For JUnit4 Tests there is a framework for these tasks: https://stefanbirkner.github.io/system-rules/ (the upgrade to JUnit5 is on going: https://github.com/stefanbirkner/system-rules/issues/55)

    0 讨论(0)
  • 2020-12-14 22:34

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

    0 讨论(0)
提交回复
热议问题