0

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);
}
matt-eo
  • 3
  • 4
  • 1
    To be frank, I don't think this needs a test at all. Basically, you are testing default functions of Java (equals, return). Also, you may be better off using a switch / case instead of 5 ifs ;) – maio290 Feb 05 '21 at 20:28
  • thank you for your feedback... this is one of the first projects I did a year ago so it can defenitely be improved :) Since I just started learning testing I thought I'd start with some easy stuff! – matt-eo Feb 05 '21 at 21:00
  • @PetterFriberg yes I had a look earlier but couldn't find a solution to my problem – matt-eo Feb 05 '21 at 21:02

0 Answers0