title: How to simulate user input for Scanner?
body: <p>I have a class in which the user interacts on a terminal window and types in certain options, based on those options it makes a switch and uses certain methods; I need to use a scanner to detect user input.</p>
  
  <p>I tried for a few days to make a test class to simulate user input but I cannot find a proper way to do it, as I cannot simulate System.in for the scanner and neither I have found any concrete information, I have seen something about buffering but I cannot use that.</p>
  
  <p>Here is an attempt, which results in a nullPointerException for the scanner - because there is no input detected.. I also tried to sleep and then set the input.</p>
  
  <p>An example of simulating System.in for Scanner would be much appreciated.</p>
  
  <pre><code>public void test1addItem()
  {
      InputStream input = new ByteArrayInputStream("".getBytes());
      String data1="1"; //Add an item option
      String data2="bread"; //The item to add
  
      input = new ByteArrayInputStream(data1.getBytes());
      //System.out.println("DATA1="+input);
      System.out.println("TEMP - 1");
      System.setIn(input);
      System.out.println("TEMP - 2");
      tsl.start(); //reference to the class which I am testing
      System.out.println("TEMP - 3");
      try {
          Thread.sleep(2000);
      } catch(InterruptedException ex) {
          Thread.currentThread().interrupt();
      }
      System.out.println("TEMP - 4");
      input = new ByteArrayInputStream(data2.getBytes());
      System.out.println("TEMP - 5");
      System.setIn(input);
      System.out.println("TEMP - 6");
  }
  </code></pre>
  
  <p>It stops at TEMP - 2, as it is a recursive method until a certain option is given to terminate the program.</p>