Issue: I'm trying to test a simple program in Java that requires user input but while I'm able to feed the input to the test, I'm only able to do so in the first called method. The error thrown is java.util.NoSuchElementException: No line found
The setup: The first method ask for user to type a command, after that and depending on the command the method will call on other methods that also ask for user input. This is where the issue arises.
Method to be tested:
public abstract class InputHandler {
// Scanner for commands, login message and instructions
public static void start() {
String fullCommand;
String actionCommand;
String commandId;
Scanner scanner = new Scanner(System.in);
// Command loop: asks for valid input and assigns id to variable if necessary
while(true) {
System.out.println("\nEnter command:");
actionCommand = scanner.nextLine().toLowerCase();
//logic to handle different length commands
}
switch (actionCommand) {
case "new lead":
newLead();
break;
case "show leads":
showLeads();
break;
case "quit":
try {
System.out.println("Goodbye!");
Thread.sleep(1000);
System.exit(0);
}catch (InterruptedException e) {
e.printStackTrace();
}
default:
System.out.println("Please enter a valid command");
}
}
}
JUnit Test:
@Test
void startTest() {
System.setIn(new ByteArrayInputStream("new lead\nGustavo Perez\n555555555\nhola@gus.io\nKurts".getBytes()));
InputHandler.start();
assertTrue(!DatabaseManager.getLeads().isEmpty());
}
Again the issue is on the test when the method is called, while it passes "new lead" as standard input (the first string in the byte array) to the Scanner, after the method start() calls the newLead() it no longer continues to pass the values in the byte array.
Thanks for any help!