0

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?

MeHead
  • 7
  • 1
  • 1
  • 5
  • 1
    So what is your question? – Michal Mar 26 '19 at 21:56
  • Just added it. Hopefully it's clear enough – MeHead Mar 26 '19 at 22:14
  • This is a fairly broad question. Maybe too broad to get a good answer. You should read about dependency injection, mockito, and why dependency injection is important for unit testing. Then come back if you have more specific questions with specific examples. – mkasberg Mar 26 '19 at 22:34

2 Answers2

3

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.

Oleksii Zghurskyi
  • 3,967
  • 1
  • 16
  • 17
0

You cas use System.in to read from standard input (probably your "console")

Antoniossss
  • 31,590
  • 6
  • 57
  • 99