The method is supposed to return false when the input string is "exit". I would like to achieve this using only JUnit5. At the moment when I run the test I get stuck in a infinite loop.
Here's the method in question:
public boolean start() {
while (true) {
System.out.println("Write action (buy, fill, take, remaining, exit):");
String input = scan.nextLine();
if (input.equals("exit")) {
System.out.println("Thank you! Bye!");
return false;
}
if (input.equals("remaining")) {
printRemaining();
}
if (input.equals("take")) {
printMoney();
}
if (input.equals("fill")) {
fill();
}
if (input.equals("buy")) {
makeCoffee();
}
return true;
}
}
And here's is what I came up with. However this gets stuck in a infinite loop when I try to run the test:
@Test
void itShould_returnFalse_When_inputIsExit() {
// Given
String exit = "exit";
InputStream sysInBackup = System.in;
ByteArrayInputStream in = new ByteArrayInputStream(exit.getBytes(StandardCharsets.UTF_8));
System.setIn(in);
// When
boolean actual = coffeeMachine.start(); // instance of the class I'm testing
// Then
assertFalse(actual);
}