mercredi 29 juillet 2015

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 suspect that I can get a pretty thorough unit test if I can somehow control the command string and keep track of the scanner object. The problem is that (for whatever reason) I'm actually not allowed to inject those two objects as arguments for this method. I need a different way to do this test. What options are there?

Aucun commentaire:

Enregistrer un commentaire