Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing data to System.in

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?

like image 698
Mesut Avatar asked Sep 28 '10 14:09

Mesut


People also ask

What is the use of system in?

System.in provides the input stream from the keyboard and InputStreamReader reads the stream. Next, a BufferedReader object is instantiated with the InputStreamReader object passed to the constructor.

What is system in read () in Java?

in. read(byte[]) System is a class in java. lang package. in is a static data member in the system class of type input stream class.

Why do we use system in Java?

System.in in java means to take input from the keyboard or user. System. out in java means to print the output to console.

What is system in in new input string reader of system in?

System. in is an object of InputStream which receives the data in the form of bytes from the keyboard. Then the task of reading and decoding the bytes into characters is done by the InputStreamReader.


2 Answers

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

like image 194
jjnguy Avatar answered Oct 14 '22 18:10

jjnguy


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 );
}
like image 44
Aaron Digulla Avatar answered Oct 14 '22 17:10

Aaron Digulla