How is it possible to run tests against a class that reads from System.in for user input?
For example:
private int getUserInput() {
Scanner scanner = new Scanner(System.in);
System.out.print("What's ya input? [1-3]: ");
return scanner.nextInt();
}
I’ve thought maybe subclassing the main class and overridding getUserInput to feed back scripted answers. Though this won’t work if you need to read System.out to decide the input.
I spent a few hours looking up Threads however couldn’t figure out how to use them for this either.
Well, you can replace
System.inusingSystem.setIn()but I would not favour that approach. Setting global state always makes your tests a bit more fragile and non-transparent.Instead you should really try to break the dependency, for example by injecting the
InputStreamthat you want to read from into your class through the class’ constructor. Once you do that, when you unit test it you can pass in your ownInputStreamthat reads from static data, and in your production code you can injectSystem.in.