junit testing for user input using Scanner

You can change the System.in stream using System.setIn() method.

Try this,

@Test
public void shouldTakeUserInput() {
    InputOutput inputOutput= new InputOutput();

    String input = "add 5";
    InputStream in = new ByteArrayInputStream(input.getBytes());
    System.setIn(in);

    assertEquals("add 5", inputOutput.getInput());
}

You have just modified the System.in field. System.in is basically an InputStream which reads from the console (hence your input in the console). But you just modified it and let the system to read from the provided inputstream instead. So it wont read from console anymore but from the inputstream provided.

Leave a Comment