I have a Java command-line program. I would like to create JUnit test case to be able to simulate System.in
. Because when my program runs it will get into the while loop and waits for input from users. How do I simulate that in JUnit?
Thanks
I have a Java command-line program. I would like to create JUnit test case to be able to simulate System.in
. Because when my program runs it will get into the while loop and waits for input from users. How do I simulate that in JUnit?
Thanks
You can write a clear test for the command line interface by using the
TextFromStandardInputStream
rule of the System Rules library.Full disclosure: I'm the author of that library.
The problem with
BufferedReader.readLine()
is that it is a blocking method which waits for user input. It seems to me that you don't particularly want to simulate that (i.e. you want tests to be fast). But in a testing context it continually returnsnull
at high speed during testing, which is irksome.For a purist you can make the
getInputLine
below package-private, and mock it: easy-peezy.... you'd have to make sure that you had a way of stopping (typically) a loop of user interaction with the app. You'd also have to cope with the fact that your "input lines" would always be the same until you somehow changed the
doReturn
of your mock: hardly typical of user input.For a non-purist who wishes to make life easy for themselves (and produce readable tests) you could put all this stuff below in your app code:
... in your test you might then go like this:
before triggering off the method in this "ConsoleHandler" class which needs input lines.