title: How to JUnit test a Method with a Scanner?
body: <p>I have a class which reads a file and takes in a user input with a scanner and if the scanner equals a part of a line in that file, it will display a string from the same line. </p>
  
  <p><strong>How would I go and create a Junit test method for this?</strong></p>
  
  <p>Here is some of my code that I want a test method for:</p>
  
  <pre><code>Scanner Input = new Scanner(System.in);
      String name = Input.nextLine();
  
      BufferedReader br;
     try{
         br = new BufferedReader(new FileReader(new File(filename)));
         String nextLine;
         while ((nextLine = br.readLine()) != null)
         {
             if (nextLine.startsWith("||"))
             {
                  int f1 = nextLine.indexOf("*");
                  int f2 = nextLine.indexOf("_");
                  fName = nextLine.substring(f1+1, f2);
                     if (name.equals(fname))
                     {
                          String[] s1 = nextLine.split("_");
                          String sName = s1[1];
                          System.out.println(sName);
                     }
             }
         }
  </code></pre>
  
  <p>my data file looks like this</p>
  
  <pre><code>||
  *Jack_Davis
  *Sophia_Harrolds
  </code></pre>
  
  <p>I have tried to use this code in my test method</p>
  
  <pre><code>@Test
  public void testgetSurname() {
      System.out.println("get surname");
      String filename = "";
      String expResult = "";
      String result = fileReader.getSurname(filename);
      assertEquals(expResult, result);
  
      filename = "datafiles/names.txt";
      String data = "Jack";
      InputStream stdin = System.in;
      try{
        System.setIn(new ByteArrayInputStream(data.getBytes()));
        Scanner scanner = new Scanner(System.in);
        System.out.println(scanner.nextLine());
      } finally {
        System.setIn(stdin);
        expResult = "Davis";
      }
      String result = fileReader.getSurname(filename);
      assertEquals(expResult, result);                
  }
  </code></pre>