I am trying to simulate multiple inputs in Java console with the help of Scanner. I need them for Unit testing but its failing only first few values are correctly taken but rest of them are ignored. Please have a look at the following code
String simulatedInput = "1\n" + "2\n" + "James\n" + "Snow\n" + "5\n" + "Mango\n" + "6\n";
InputStream in = new ByteArrayInputStream(simulatedInput.getBytes());
Scanner scanner = new Scanner(in);
int index = 0;
if (scanner.hasNextInt()) {
index = scanner.nextInt();
}
if (index != 1) {
System.out.println("#1) Should be 1");
}
if (scanner.hasNextInt()) {
index = scanner.nextInt();
}
if (index != 2) {
System.out.println("#2) Should be 2");
}
index = -1;
String value = null;
if (scanner.hasNextLine()) {
value = scanner.nextLine();
}
if (!"James".equals(value)) {
System.out.println("#3) Should be 'James' but |" + value + "|");
}
if (scanner.hasNextLine()) {
value = scanner.nextLine();
}
if (!"Snow".equals(value)) {
System.out.println("#4) Should be 'Snow' but |" + value + "|");
}
if (scanner.hasNextInt()) {
index = scanner.nextInt();
}
if (index != 5) {
System.out.println("#5) Should be 5 but " + index);
}
if (scanner.hasNextLine()) {
value = scanner.nextLine();
}
if (!"Mango".equals(value)) {
System.out.println("#6) Should be 'Mango' but |" + value + "|");
}
if (scanner.hasNextInt()) {
index = scanner.nextInt();
}
if (index != 6) {
System.out.println("#7) Should be 6 but " + index);
}
System.out.println("*** There should be the only line ***");
and the result is as follows, test # 1 and 2 passed but rest are failing from input that is expected to be James
#3) Should be 'James' but ||
#4) Should be 'Snow' but |James|
#5) Should be 5 but -1
#6) Should be 'Mango' but |Snow|
#7) Should be 6 but 5
*** There should be the only line ***
Please note I cannot change code, as I am unit testing this code, I can only change my simulated input. Can this be fixed?
Response to possible duplicate
This is not a duplicate question, I cannot change the code to consume extra \n, I can only make changes in simulated input only.