Search code examples
javajunit4console-input

JUnit Testing Console Input Application


I am trying to use JUnit to test a java application which takes input from the console to make choices in the program. Here is a snippet of the program I am trying to test below.

PS: I am new to JUnit testing so a clear and simple answer would be appreciated.

public void mainMenu(){
   String input;
   while (true){
      System.out.println("1. view     2. Set-Up     3. Exit");
            input = getInputFromConsole().trim();

            switch (input.charAt(0)) {
               case '1':
                  view();
                  break;
               case '2':
                  setUp();
                  break;
               case '3':
                  System.exit(0);
                  break;
   }
}

How would I create a test case where the input would be eg. '1' but the input is given from the console?


Solution

  • If you get input from System.in, then for testing you can change it with System.setIn() method.

    Lacking your specific details, here is a sketch example:

    @Test
    public void takeUserInput() {
        InputStream in = new ByteArrayInputStream("1".getBytes());
        System.setIn(in);
        // instantiate and exercise your object under test
        // assert something meaningful
    }
    

    However, in general I would recommend to abstract away details of taking input from user. For example by introducing some UserInput interface. Then you can inject this to your class under test. This will help to have any input provider: console, web, DB etc. Having interface in place you will be able to stub any user input. The good library for stubbing is Mockito.