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?
What you want to do is use the method
setIn()
fromSystem
. This will let you pass data intoSystem.in
from junit.Replace it for the duration of your test:
My solution currently (in 2018) is:
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: