Basically, I’m writing a Java Command-line application which accept parameter from user by readLine. Ex, if the user press “1” it will ask which book the user wants to check out, the user can press the number of the book by “1” or “2” … So, the application accepts user parameter two times. And I’m trying to use TDD to test the application alongside as well.
Here is the problem.
If I do something like this to simulate user input
System.setIn(new ByteArrayInputStream(PRESS_TWO.getBytes())); // set the first option
Program.main(new String[]{}); // run the program
System.setIn(new ByteArrayInputStream(PRESS_ONE.getBytes())); // set the second option
The first step that waits for user to choose option is ok, but it will go right through the second step without waiting for the second input. How can I simulate this in JUnit?
Thanks
This is how I read input
try {
i1 = Integer.parseInt(reader.readLine());
}
catch (Exception e) {
System.out.println("Enter a valid integer!!");
}
if (i1 == 1) {
System.out.println(" 1. Book1 ");
System.out.println(" 2. eBook2 ");
System.out.println(" 3. Book3 ");
}
else if (i1 == 2) {
System.out.println(" Which one do you want?: ");
int i2 = 0;
try {
i2 = Integer.parseInt(reader.readLine());
}
catch (Exception e) {
// Do you know what numbers are!!!
System.out.println("Enter a valid integer!!");
}
}
It depends on how your code reads the input, but I would assume that once the end of the first
ByteArrayInputStreamis reached, your code sees end-of-file and terminates. Try to combine the two streams into one (separated by a newline).