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?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With