title: Test java programs that read from stdin and write to stdout
body: <p>I am writing some code for a programming contest in java. The input to the program is given using stdin and output is on stdout. How are you folks testing programs that work on stdin/stdout? This is what I am thinking:</p>
  
  <p>Since System.in is of type InputStream and System.out is of type PrintStream, I wrote my code in a func with this prototype:</p>
  
  <pre><code>void printAverage(InputStream in, PrintStream out)
  </code></pre>
  
  <p>Now, I would like to test this using junit. I would like to fake the System.in using a String and receive the output in a String.</p>
  
  <pre><code>@Test
  void testPrintAverage() {
  
      String input="10 20 30";
      String expectedOutput="20";
  
      InputStream in = getInputStreamFromString(input);
      PrintStream out = getPrintStreamForString();
  
      printAverage(in, out);
  
      assertEquals(expectedOutput, out.toString());
  }
  </code></pre>
  
  <p>What is the 'correct' way to implement getInputStreamFromString() and getPrintStreamForString()? </p>
  
  <p>Am I making this more complicated than it needs to be?</p>