How to simulate multiple user input for JUnit

java, junit

Solution

Just using a "new line" should be enough.

String simulatedUserInput = "input1" + System.getProperty("line.separator")
    + "input2" + System.getProperty("line.separator");

InputStream savedStandardInputStream = System.in;
System.setIn(new ByteArrayInputStream(simulatedUserInput.getBytes()));

// code that needs multiple user inputs

System.setIn(savedStandardInputStream);

Problem

Right now I have this ``` ByteArrayInputStream in = new ByteArrayInputStream("2".getBytes()); System.setIn(in); //code that does something with user inputs ``` But the issue is that in //code that does something I have multiple user input prompts, is it possible to form a list of the user input and have it pick up the corresponding input when the time comes? I tried doing silly things like "2\n2\n10\nHello\n".getBytes() but that didn't work. EDIT: I am getting my user input with a Scanner object: ``` Scanner inputScanner = new Scanner(System.in); inputScanner.nextLine(); ```

Original source