1

I want to test the mainMenu of a program which receives user input and calls a function/method depending on the input.

public void mainMenu() {
    System.out.println("1. Schedule a meeting");
    System.out.println("2. Book vacation dates");
    System.out.println("3. Check room availability");

try {
            int userInput = Integer.parseInt(inputOutput("Please enter the number that corresponds to the option that you want to proceed with."));

        if (userInput >= 0 && userInput <=6) {
            if (userInput == 1) {
                this.scheduleMeeting();
            }
            if (userInput == 2){
                this.scheduleVacation();
            }
            if (userInput == 3){
                this.checkRoomAvailability();
         } else {
            System.out.println("Please enter a number from 0 - 6");
            this.mainMenu();
        }
    } catch (NumberFormatException e) {
        System.out.println("Please enter a number from 0 - 6");
        this.mainMenu();
    }
}

To test the userInput I think it would be something like:

    ByteArrayInputStream in = new ByteArrayInputStream("2".getBytes());
    System.setIn(in);

But how would I test the expected result when it's a function call? Should I be using Mockito and how would I implement it?

2 Answers 2

1

1) You can make a 'mock' test. Read Mockito.

2) You can pass an input parameter of user like parameter of method.

3) just use fake value to test. Input your own integer and write a test. You need just to check if method work correct and doesn't matter who input this value.

Sign up to request clarification or add additional context in comments.

1 Comment

So I've been looking around, would it be something like this: when(mockedObject.scheduleMeeting()).thenReturn("scheduleMeeting called") ? Would this work? And what do you mean at 2?
0

you can check an example here

Different approach can be make this method more testable by passing IN and OUT as parameters:

public static int testUserInput(InputStream in,PrintStream out) {
   Scanner keyboard = new Scanner(in);
    out.println("Give a number between 1 and 10");
    int userInput = keyboard.nextInt();

    if (userInput >= 0 && userInput <=6) {
        if (userInput == 1) {
            this.scheduleMeeting();
        }
        if (userInput == 2){
            this.scheduleVacation();
        }
        if (userInput == 3){
            this.checkRoomAvailability();
     } else {
        System.out.println("Please enter a number from 0 - 6");
        this.mainMenu();
    }
} catch (NumberFormatException e) {
    System.out.println("Please enter a number from 0 - 6");
    this.mainMenu();
}

    return input;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.