Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a void method with no arguments

I need to test a class to determine if a relevant action has taken place given a certain input. The code goes something like this:

protected static void receiveInput() {
    String command;
    boolean b = true;
    Scanner scanner = new Scanner(System.in);

    while (b) {

        command = scanner.next();
        switch(command) {

            case "first":
                System.out.println("First!");
                break;

            case "second":
                System.out.println("Second!");
                break;

            case "third":
                System.out.println("Third!");
                break;

            default:
                System.out.println("\n***** Invalid *****\n"); 
        }

        System.out.println("\n");
    }

    scanner.close();
}

I can probably get a pretty thorough unit test if I can somehow control the command string and keep track of the scanner object. For some reason, I'm actually not allowed to inject those two objects as arguments for this method. What options are there for doing this test a different way?

like image 329
Miles Peterson Avatar asked Jul 29 '15 20:07

Miles Peterson


Video Answer


1 Answers

This is a perfect example for making functions more testable. This function takes no input and produces no output, affecting the world only via side effect, making it completely untestable through standard means.

To refactor this function to make it more testable:

  • Don't ask the user for input via scanner, take the user's input as an input parameter.
  • Don't print the result, return it.

The caller of the function can then decide how to provide the inputs and what to do with the output. Your modified program can ask for user input, call the function, then print the output. A testing framework can supply the input from a list of inputs to test, and check the outputs against the expected values.

like image 88
MattPutnam Avatar answered Oct 20 '22 18:10

MattPutnam